当属性被添加到 Python 中的 class 时执行方法
Perform method when an attribute is added to a class in Python
我想实例化一个类,比如 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
您可以为特定的 属性 定义自定义 setter。
@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
我想实例化一个类,比如 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
您可以为特定的 属性 定义自定义 setter。
@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