笔记:静态方法和类方法

静态方法和类方法

它们分别包装于staticmethod和classmethod类的对象中。静态方法的定义没有参数self,可直接通过类来调用。类方法定义包含类似于self的参数,通常被命名为cls。类方法也可以通过对象直接调用,但参数cls将自动关联到类。

示例

class MyClass():

    @staticmethod
    def smeth():
        print('This is a static method')

    @classmethod
    def cmeth(cls):
        print('This is a class method of', cls)

        
# 无需实例化类
MyClass().smeth()
MyClass().cmeth()

# This is a static method
# This is a class method of <class '__main__.MyClass'>

猜你喜欢

转载自www.cnblogs.com/dhzg/p/11564377.html