1 说明
大多数情况,@classmethod和@staticmethod效果一样。但是如果有继承关系,情况有所不同。
2 @classmethod的真实意义
2.1 类生成例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class A(object):
bar = 1
def func1(self):
print ('foo')
@classmethod
def func2(cls):
print ('func2')
print (cls.bar)
cls().func1() # 调用 foo 方法
A.func2() # 不需要实例化
2.1 @classmethod类工厂
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
person = Person('Adam', 19)
person.display()
person1 = Person.fromBirthYear('John', 1985)
person1.display()
3 @classmethod和@staticmethod的区别
假设您创建了 Foo 的子类并在子类上调用了 create_new 方法
class Bar(Foo):
pass
obj = Bar.create_new()
然后这个基类将导致一个新的 Bar 对象被创建......
class Foo:
@classmethod
def create_new(cls):
return cls()
而这个基类会导致创建一个新的 Foo 对象
class Foo:
@staticmethod
def create_new():
return Foo()
采取哪一个?取决于你想要的行为。
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@staticmethod
def fromFathersAge(name, fatherAge, fatherPersonAgeDiff):
return Person(name, date.today().year - fatherAge + fatherPersonAgeDiff)
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
class Man(Person):
sex = 'Male'
man = Man.fromBirthYear('John', 1985)
print(isinstance(man, Man))
man1 = Man.fromFathersAge('John', 1965, 20)
print(isinstance(man1, Man))