zoukankan      html  css  js  c++  java
  • python内置装饰器---- staticmethod和classmethod

    staticmethod

    staticmethod 只能作为函数装饰器应用。其作用为将一个函数转换为静态方法。下面一段代码中,若不在def get(argv1)上添加装饰器staticmethod.
    在执行代码test.get("hello") 将会出现 TypeError: get() takes 1 positional argument but 2 were given。
    这说明 在不添加装饰器staticmethod,Python 解释器仅仅将def get(argv1) 解释为类C 内部定义的函数;添加后,则将其解释为类C 的静态方法。

    class C:
        def __init__(self):
            self._item = 1
        
        @staticmethod
        def get(argv1):
            # print(self._item)
            print(argv1)
    
    test = C()
    test.get('hello')
    C.get('hello')
    

    classmethod

    classmethod,与staticmethod类似, 只能作为函数装饰器应用。其作用为将一个函数转换为类方法。若不在def get(argv1)上添加装饰器classmethod.
    在执行代码时 C.get('hello')将会出现 TypeError: get() missing 1 required positional argument: 'argv1' 。
    这说明 在不添加装饰器classmethod,Python 解释器不会讲C作为cls 传输给 get(cls,argv) 。

    class C:
        def __init__(self):
            self._item = 1
       
        @classmethod
        def get(cls, argv1):
            # print(self._item)
            print(argv1)
    test = C()
    test.get('hello')
    C.get('hello')
    

    小结

    staticmethod classmethod
    区别 讲func 装换为静态方法 将func 转换为类方法
    相似点 调用方式相同
  • 相关阅读:
    shutil模块详解
    pycharm连接服务器
    python中__name__属性的使用
    ORM学习笔记
    ORM连表操作
    python操作mysql实例
    python登录项目
    pycharm建立第一个django工程-----windows中
    打印顺序
    shell脚本
  • 原文地址:https://www.cnblogs.com/Finding-bugs/p/14178436.html
Copyright © 2011-2022 走看看