使用@classmethod修饰的为类方法,使用 @staticmethod修饰的为静态方法,具体使用如下:
类方法
class Person:
hair='black'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self,content):
print(content)
@classmethod
def classfunc(cls):
print("classfunc:",cls.hair)
@staticmethod
def staticfunc(cls):
print("staticfunc",cls)
me=Person('me',10)
me.hair='red'
print(Person.hair)
Person.classfunc()
print('------------')
print(me.hair)
me.classfunc()
输出如下:
black
classfunc: black
------------
red
classfunc: black
可以看到,即使使用实例对象(me)去调用类方法,该方法第一个参数自动绑定的还是该类(Person)。
静态方法
class Person:
hair='black'
def __init__(self,name,age):
self.name=name
self.age=age
def say(self,content):
print(content)
@classmethod
def classfunc(cls):
print("classfunc:",cls.hair)
@staticmethod
def staticfunc(cls):
print("staticfunc",cls)
me=Person('me',10)
Person.staticfunc('Person')
Person.staticfunc()
输出如下:
staticfunc Person
Traceback (most recent call last):
File "test.py", line 16, in <module>
Person.staticfunc()
TypeError: staticfunc() missing 1 required positional argument: 'cls'
可见静态方法没有自动绑定第一个参数,故需要传参。利用实例对象me调用同理。