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 转换为类方法
    相似点 调用方式相同
  • 相关阅读:
    高可用性机制
    Moodle课程资源系统安装
    Windows 10 安装 chocolatey
    centos7安装samba服务器
    抽签网页板代码
    CentOS7系统操作httpd服务
    centos7.2下放行端口
    centos7没有netstat命令的解决办法
    Linux
    Linux下常用服务的端口号超详细整理
  • 原文地址:https://www.cnblogs.com/Finding-bugs/p/14178436.html
Copyright © 2011-2022 走看看