I would like to instantiate a class, say, Fighter
with and without the attribute weapon_size
. But when the attribute weapon_size
is set (either at instantiation or later) I want to run some method which adds another attribute damage
(and perhaps does some other calculations). I'm trying to do this by overloading the setattr function as below.
My question: is this the correct [and sensible] way to do this?
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