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 转换为类方法
    相似点 调用方式相同
  • 相关阅读:
    CSS选择器之伪类选择器(元素)
    CSS选择器之基本选择器+属性选择器
    bugku 点击1000000次
    bugku web 5
    bugku 矛盾 30
    bugku 域名解析题 50
    bugku 好多压缩包
    六子冲 模拟棋盘
    poj3126 Prime Path(c语言)
    poj1426 Find The Multiple(c语言巧解)
  • 原文地址:https://www.cnblogs.com/Finding-bugs/p/14178436.html
Copyright © 2011-2022 走看看