Python装饰器

1.@property

修饰方法,使方法可以像属性一样访问,此时方法已经不是callable的了,也就是不能加括号。

Python装饰器_第1张图片

2.@classmethod

将函数转换为类方法,类不需要实例化就可以直接调用。对于实例方法,参数self指向实例;对于类方法,参数cls指向当前类。

class C:
    @classmethod
    def f(cls, arg1, arg2, ...):
        ...

3.@staticmethod

将函数转换为类方法,不传入类和实例的属性。

class C:
    attr = 'test'    # 类属性
   
    def __init__(self, name):
        self.name = name    # 实例属性
    
    @staticmethod
    def f(arg1, arg2, ...):
        ...

[email protected]

 强制子类实现此方法

你可能感兴趣的:(Python,Python基础知识)