classmethod、staticmethod是分别指定函数为动态方法还是静态方法,先看下面这个例子:
class Person:
def __init__(self, name):
self.name = name
@classmethod
def work(cls, name):
return "%s is working!!!" % name
@staticmethod
def eat(name):
return "%s is eating!!!" % name
def sleep(self):
return "%s is eating!!!" % self.name
print(Person.work)
print(Person.eat)
print(Person.sleep)
打印结果为:
<bound method Person.work of <class '__main__.Person'>>
<function Person.eat at 0x00000000025DAA60>
<function Person.sleep at 0x00000000025DAAE8>
可以看到@classmethod的函数是绑定的method而不是function,那么method和function有什么区别呢,先看下说明:
function —— A series of statements which returns some value toa caller. It can also be passed zero or more arguments which may beused in the execution of the body.
method —— A function which is defined inside a class body. Ifcalled as an attribute of an instance of that class, the methodwill get the instance object as its first argument (which isusually called self).
也就是说method是绑定在类里面的方法,再看下面这组对比示例:
def work(name):
return "%s is eating!!!" % name
class Person:
def __init__(self, name):
self.name = name
def sleep(self):
return "%s is eating!!!" % self.name
print(work)
print(Person.sleep)
person = Person("xiaoming")
print(person.sleep)
打印结果为:
<function work at 0x00000000029FA620>
<function Person.sleep at 0x00000000029FAA60>
<bound method Person.sleep of <__main__.Person object at 0x00000000023FA860>>
可以看到,在我们实例化类过后,函数会变成这种bound method,即绑定实例的方法。
当然,@classmethod常常是用来设置类,比如举一个例子:
class Person:
def __init__(self, name):
self.name = name
@classmethod
def work(cls):
cls.__init__(cls, "小明代工")
print("%s is working!!!" % cls.name)
def work_pub(self):
print("%s is working!!!" % self.name)
xiaohong = Person("小红")
xiaohong.work()
xiaohong.work_pub()
打印结果为:
小明代工 is working!!!
小红 is working!!!
如果函数中没有包含实例必须的变量时可以使用staticmethod,无需传入实例,也不能传入。
class Person:
def __init__(self, name):
self.name = name
@staticmethod
def work(name): # 不能传入self,所以整个函数内部也不会有self
print("%s is working!!!" % name)
Person.work("xiaoming")
# 这里打印结果为 xiaoming is working!!!
这样做的好处就是不用实例化,可以外部直接调用work函数。