使用内置函数 更改更新方法以更新现有属性hasattr()
,setattr()
和getattr()
。
def upgrade(self, attribute, value):
if hasattr(self, attribute):
setattr(self, attribute, getattr(self, attribute) + value )
else:
raise AttributeError("Can't upgrade non-existent attribute '{}'.".format(attribute))
请注意,我还将使用该__dict__
属性来更轻松地设置您的实例:
class Ship:
# types is a class variable, and will be the same for all instances,
# and can be referred to by using the class. ie `Ship.types`
types = {
"schooner": {'weight':50, 'speed':30, 'poopdeck':18},
"galleon": {'weight':30, 'speed':14, 'poopdeck':14},
"default": {'weight':11, 'speed':11, 'poopdeck':11}
}
def __init__(self, name):
self.name = name
# we update the instance dictionary with values from the class description of ships
# this means that instance.speed will now be set, for example.
if name in Ship.types:
self.__dict__.update(Ship.types[name])
else:
self.__dict__.update(Ship.types["default"])
def upgrade(self, attribute, value):
if hasattr(self, attribute):
setattr(self, attribute, getattr(self, attribute) + value )
else:
raise AttributeError("Can't upgrade non-existent attribute '{}'.".format(attribute))
ship = Ship("schooner")
print(ship.speed) #=> 30
ship.upgrade("speed", 10)
print(ship.speed) #=> 40