在Person
对象中,已经有了对广告资源的支持,以及Person
时的支持
对象将获取Weapon
对象或Food
对象,该对象将转到清单。对于
我们的Tribute
对象,我们希望有一种方法可以从中检索Weapon
和Food
对象
库存。
在Tribute
类get weapons()
中创建一个新方法,该方法将返回一个
Weapon
当前在其广告资源中有Tribute
个对象的元组
class Tribute(Person):
def get_weapon(self):
for item in self.get_inventory():
if isinstance(item, self.RangedWeapon):
return tuple(item)
else:
pass
cc = Tribute("Chee Chin", 100)
chicken = Food("chicken", 5)
aloe_vera = Medicine("aloe vera", 2, 5)
bow = RangedWeapon("bow", 4, 10)
sword = Weapon("sword", 2, 5)
Base = Place("base")
Base.add_object(cc)
Base.add_object(chicken)
Base.add_object(aloe_vera)
Base.add_object(bow)
Base.add_object(sword)
cc.take(bow) # Chee Chin took bow
cc.take(sword) # Chee Chin took sword
cc.take(chicken) # Chee Chin took chicken
cc.take(aloe_vera) # Chee Chin took aloe_vera
def add_object(self, new_object):
if isinstance(new_object, Thing) or isinstance(new_object, LivingThing):
self.objects.append(new_object)
new_object.place = self
else:
GAME_LOGGER.warning("You can only add Thing or LivingThing to {}".format(self.get_name()))
def named_col(col):
# Only accepts tuple/list
type_col = type(col)
if type_col != list and type_col != tuple:
return None
return type_col(map(lambda x: x.get_name() if isinstance(x, NamedObject) else x, col))
当我尝试print(named_col(cc.get_weapons()))
时收到错误
AttributeError: 'RangedWeapon' object has no attribute 'owner'
class Thing(MobileObject):
def __init__(self, name):
super().__init__(name, None)
self.owner = None
def set_owner(self, owner):
self.owner = owner
def get_owner(self):
return self.owner
def is_owned(self):
return self.owner is not None
RangedWeapon之前已在此类class RangedWeapon(Weapon):
答案 0 :(得分:1)
下面:
if isinstance(item, self.RangedWeapon):
return tuple(item)
你没有返回所有武器的元组,你将一个武器从命名元组转换为常规元组并返回单个对象。这剥离了命名属性,因此错误。相反,你需要像:
def get_weapon(self):
weapons = []
for item in self.get_inventory():
if isinstance(item, RangedWeapon):
weapons.append(item)
return tuple(weapons)
您还应该完全将get_weapon
(cc = Tribute("Chee Chin", 100)
之后)之外的所有代码移到课堂外,即将所有代码全部移除。
答案 1 :(得分:0)
尝试:
def get_weapons(self):
weapons = []
for item in self.get_inventory():
if isinstance(item, RangedWeapon):
weapons.append(item)
elif isinstance(item, Weapon):
weapons.append(item)
return tuple(weapons)