普通类方法 def method(self)
类方法 @classmethod
静态方法 @staticmethod

装饰器给类添加属性


def add_attr(name):
    def wrapper(cls):
        cls.name = name
        return cls
    return wrapper
    
@add_attr('jerry') # add_attr('jerry')(Person)
class Person():
    def method(self):
        print('method~~~~~~~~')

print(Person.__dict__)
----------------------------------------------
{'__module__': '__main__', 'method': <function Person.method at 0x000001AB13B5C0D0>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None, 'name': 'jerry'}

普通类


在介绍类方法和静态方法之前先回顾下普通类方法的调用

class Person():
    def __init__(self,name):
        self.name = name
    def method(self):
        print('method~~~~~~~~',self.name)

# print(Person.method())# 报错
Person('jerry').method() # 实例绑定self,必须用实例来调用

类方法


class Person:    
    @classmethod    
    def class_method(cls,a,b): 
        print(cls)
        print(a,b)
        cls.HEIGHT = 170 # 给类添加属性
        
Person.class_method(1,2) # 通过类调用
Person().class_method(3,4) # 通过类的实例调用
print(Person.__dict__)
----------------------------------
<class '__main__.Person'>
1 2
<class '__main__.Person'>
3 4
{'__module__': '__main__', 'class_method': <classmethod object at 0x000001AB13BEA400>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None, 'HEIGHT': 170}
  • 类方法:使用@classmethod装饰器修饰的方法
  • 必须至少有一个参数,为cls(可为其他标识符),指代调用者即类对象自身
  • 通过cls可以直接操作类的属性,可为类添加属性
  • 类似 C++,java 中的静态方法

静态方法


class Person: 
    HEIGHT = 170
    @staticmethod    
    def static_method(): 
        print(Person.HEIGHT)

Person.static_method() # 通过类调用
Person().static_method()# 通过类实例调用
  • 静态方法:使用@staticmethod装饰器修饰的方法
  • 调用时,不会隐式的传入参数
  • 静态方法,只是表明这个方法属于这个名词空间。函数归在一起,方便组织管理

方法比较


请自行运行比较并理解

class Person:    
    def method(self):
        print("{}'s method".format(self))    
    @classmethod    
    def class_method(cls): # cls是什么
        print(cls)
        cls.HEIGHT = 170    
    @staticmethod    
    def static_methd():
        print(Person.HEIGHT)

 
# print(1, Person.method()) # 报错
print(2, Person.class_method()) # 
print(3, Person.static_methd()) # 
print(Person.__dict__)

tom = Person()
print(4, tom.__class__.class_method()) #
print(5, tom.method()) # 
print(6, tom.class_method()) # 
print(7, tom.static_methd()) # 

参考


  • magedu