classCar(object):def__init__(self,make,model,year,color):self.make=makeself.model=modelself.year=yearself.color=color@propertydefdescription(self):""" Return a description of this car. """return"%s%s%s%s"%(self.color,self.year,self.make,self.model)
classAttributeInitType(type):def__call__(self,*args,**kwargs):""" Create a new instance. """## First, create the object in the normal default way.obj=type.__call__(self,*args)## Additionally, set attributes on the new object.forname,valueinkwargs.items():setattr(obj,name,value)## Return the new object.returnobj
classCar(object):__metaclass__=AttributeInitType@propertydefdescription(self):""" Return a description of this car. """return" ".join(str(getattr(self,attr,"Unknown"))forattrinself.__dict__)
在Python3中需要提供一个命名参数:
1
2
3
4
5
classCar(object,mateclass=AttributeInitType):@propertydefdescription(self):""" Return a description of this car. """return" ".join(str(value)forvalueinself.__dict__.values())