python 的@classmethod 理解
@classmethod
@calssmethod的作用就是“可以不需要实例化,直接类名.方法名()来调用。这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁”
@classmethod的作用实际是可以在class内实例化class,一般使用在有工厂模式要求时。作用就是比如输入的数据需要清洗一遍再实例化,可以把清洗函数定义在class内部并加上@classmethod装饰器已达到减少代码的目的。
总结起来就是@class method可以用来为一个类创建一些预处理的实例。
class Data_test2(object):
day=0
month=0
year=0
def init(self,year=0,month=0,day=0):
self.day=day
self.month=month
self.year=year
@classmethod
def get_date(cls,data_as_string):
#这里第一个参数是cls, 表示调用当前的类名
year,month,day=map(int,data_as_string.split('-'))
date1=cls(year,month,day) #返回的是一个初始化后的类
return date1
def out_date(self):
print("year :",self.year)
print("month :",self.month)
print("day :",self.day)
在Date_test类里面创建一个成员函数, 前面用了@classmethod装饰。 它的作用就是有点像静态类,比静态类不一样的就是它可以传进来一个当前类作为第一个参数。那么如何调用呢?
r=Data_test2.get_date(“2020-1-1”)
r.out_date()
Map 函数的用法:
year,month,day=map(int,data_as_string.split(‘-’))
这样子等于先调用get_date()进行处理,然后怒才使用Date_test的构造函数初始化
这样的好处就是你以后重构类的时候不必要修改构造函数,只需要额外添加你要处理的函数,然后使用装饰器@classmethod就可以
1.深入理解实例
1)Factory methods (工厂方法模式)
工厂模式即用户只需要通过固定的接口来获得一个对象的实例,降低了维护的复杂性
class Pizza(object):
def init(self, ingredients): #ingredient:原料种类
self.ingredients = ingredients
@classmethod
def from_fridge(cls, fridge):
return cls(fridge.get_cheese() + fridge.get_vegetables())
这里的class method, from_fridge( cls, fridge) 返回Pizza对象,这个Pizza是冰箱里的Pizza。假如我们用静态方法来写的话,还需要在函数中hardcode the Pizza class name,继承Pizza。 在Python官方doc中也有提到:
Also see classmethod() for a variant that is useful for creating alternate class constructors.
总结起来就是,class method可以用来为一个类创建一些预处理的实例。
2)调用static method
看这个例子:
class Pizza(object):
def init(self, radius, height):
self.radius = radius
self.height = height
@staticmethod
def compute_area(radius):
return math.pi * (radius ** 2)
@classmethod
def compute_volume(cls, height, radius):
return height * cls.compute_area(radius) #调用@staticmethod方法
def get_volume(self):
return self.compute_volume(self.height, self.radius)