self
作为实例方法的第一个参数cls
作为类方法的第一个参数也就是,类方法需要创建实例后才能调用,如:
class Test:
def hello(self, name):
print ('hello ', name)
obj = Test()
obj.hello('Rahul')
而类方法(或静态方法),不依赖是否创建了实例,可以通过类名直接调用,这就不同self
而是用cls
:
class Test:
def hello(cls, name):
print ('hello ', name)
Test.hello('haha')
参考:reference