我希望实例化一个类,例如Fighter
,包含和不包含属性weapon_size
。但是当设置属性weapon_size
时(无论是在实例化还是以后),我想运行一些方法来添加另一个属性damage
(并且可能会进行其他一些计算)。我试图通过重载 setattr 函数来执行此操作,如下所示。
我的问题:这是正确的[和明智的]方法吗?
class Fighter(object):
def __init__(self, prenom, weapon_size = None):
self._prenom = prenom
self._weapon_size = weapon_size
if not weapon_size is None:
self.AddWeapon(weapon_size)
def __setattr__(self, name, value):
if name == "weapon_size":
print "Adding weapon"
self.AddWeapon(value)
self.__dict__['_' + name] = value
else:
self.__dict__[name] = value
def AddWeapon(self, x):
self._damage = x/2.
@property
def weapon_size(self):
"Weapon size"
return self._weapon_size
@property
def prenom(self):
"First name"
return self._prenom
U = Fighter('Greg')
U.weapon_size = 9
print U.weapon_size, U._damage
>> 9 4.5
W = Fighter('Jeff', weapon_size = 11)
print W.weapon_size, W._damage
>> 11 5.5
答案 0 :(得分:3)
您可以为特定属性定义自定义设置器。
@weapon_size.setter
def weapon_size(self, value):
# custom code here
self._weapon_size = value
编辑:但实际上,在一天结束的时候,我觉得你干得更干净了:
class Fighter(object):
def __init__(self, prenom, weapon_size=None):
...
self.weapon_size = weapon_size
...
@property
def damage(self):
if self.weapon_size:
return self.weapon_size / 2
return None