• 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 转换为类方法
    相似点 调用方式相同
  • 相关阅读:
    ExportToExcel(工作笔记)
    EXCEL中的公式
    HTML基础(二)
    .NET开发人员必知的八个网站
    HTML基础(一)
    Extjs学习笔记(消息框)
    The diff between throw and throw e
    工作中遇到的一些小知识点(备查)
    ASP.NET页面在IE缓存问题的解决
    URL中的"#"
  • 原文地址:https://www.cnblogs.com/Finding-bugs/p/14178436.html
Copyright © 2020-2023  润新知