我正在开发一款小型格斗游戏,作为一种学习体验,现在我正在努力实施一个可以购买武器的商店。
我决定为商店使用一个类,并将其作为类方法完成。但我不确定如何从Weapon
类获取所有数据并在Store
类中使用它。这不是很漂亮,但到目前为止我还有:
抱歉拼写错误。
class Item(object):
'''Anything that can be used or equiped.'''
def __init__(self, _id, desc, cost):
self._id = _id
self.desc = desc
self.cost = cost
class Weapon(Item):
def __init__(self, _id, desc, dam):
self._id = _id
self.desc = desc
self.dam = dam
def __str__(self):
return self._id
class Store(object):
dagger = Weapon('Dagger', 'A small knife. Weak but quick.', 'd4')
s_sword = Weapon('Short Sword', 'A small sword. Weak but quick.', 'd6')
l_sword = Weapon('Long Sword', 'A normal sword. Very versatile.', 'd8')
g_sword = Weapon('Great Sword', 'A powerful sword. Really heavy.', 'd10')
w_teir_1 = [dagger, s_sword, l_sword]
w_teir_2 = [w_teir_1, g_sword]
def intro(self):
print 'Welcome, what would you like to browse?'
print '(Items, weapons, armor)'
choice = raw_input(':> ')
if choice == 'weapons':
self.show_weapons(self.w_teir_1)
def show_weapons(self, teir):
for weapon in teir:
i = 1
print str(i), '.', teir._id
i += 1
raw_input()
我无法获得show_weapon
函数来打印武器的_id。我所能做的就是让它打印原始对象数据。
编辑:当我通过_id
方法传递列表w_teir_1
时,我已经弄明白了如何显示武器的show_weapons
。但是,当我尝试推送w_teir_2
时,我收到此错误:AttributeError: 'list' object has no attribute '_id'
答案 0 :(得分:1)
您需要更改最后一个print
stmt,如下所示,因为您正在迭代列表。 _id
属性仅存在于该列表中的元素。
print str(i), '.', weapon._id
或
print str(i) + '.' + weapon._id
更新
def show_weapons(self, teir):
for weapon in teir:
if isinstance(weapon, list):
for w in weapon:
i = 1
print str(i), '.', w._id
i += 1
raw_input()
else:
i = 1
print str(i), '.', weapon._id
i += 1
raw_input()