我从来没有使用@classmethod而且我没有想到任何使用它的例子,我知道它是如何工作的但是我不知道什么时候用它来举例
class Example:
def __init__(self,param1,param2):
self.param1 = param1
self.param2 = param2
@classmethod
def my_method(cls,param1,param2):
return cls(param1,param2)
example = Example.my_method(1,2)
print(example)
输出:
<__main__.Example object at 0x02EC57D0>
但为什么不这样做呢?
class Example:
def __init__(self,param1,param2):
self.param1 = param1
self.param2 = param2
def my_method(self,param1,param2):
return Example(param1,param2)
example = Example(1,2)
method = example.my_method(3,4)
print(method)
输出:
<__main__.Example object at 0x02EC57D0>
这是相同的结果,但是当我可以使用classmethod时,它不会浮现在脑海中
python中有3种方法:
class Person():
species='homo_sapiens' # This is class variable
def __init__(self, name, age):
self.name = name # This is instance variable
self.age = age
def show(self):
print('Name: {}, age: {}.'.format(self.name, date.today().year - self.age))
@classmethod
def create_with_birth_year(cls, name, birth_year):
return cls(name, date.today().year - birth_year)
@classmethod
def print_species(cls):
print('species: {}'.format(cls.species))
@staticmethod
def get_birth_year(age):
return date.today().year - age
class Teacher(Person):
pass
1)实例方法(show)需要一个实例,必须使用self作为第一个参数。它可以通过self访问实例并影响实例的状态。
2)类方法(create_with_birth_year和print_species)不需要实例,并使用cls来访问类并影响类的状态。我们可以使用@classmethod创建工厂,例如:
navy = Person.create_with_birth_year('Navy Cheng', 1989)
navy.show()
这个工厂可以继承:
zhang = Teacher.create_with_birth_year('zhang', 1980)
print(type(zhang))
和class方法可以使用访问类变量:
Person.print_species()
3)静态方法(get_birth_year)不需要特殊参数(self或cls),并且将改变类或实例的任何状态。它可以提供关于类的一些辅助函数。