在上使用一个类中另一个类中的属性

2024-09-29 18:59:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个小的战斗游戏作为学习经验,现在我正在开发一个商店,你可以在那里购买武器。
我决定为商店使用一个类,并将你能在其中做的一切都作为一个类方法。但是我不确定如何从我的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。我所能做的就是让它打印原始对象数据

编辑:当我通过show_weapons方法传递列表w_teir_1时,我已经知道了如何显示武器的_id。但是当我试图推动w_teir_2通过时,我得到了这个错误:AttributeError: 'list' object has no attribute '_id'


Tags: selfidobjectdefshowdescclasscost
1条回答
网友
1楼 · 发布于 2024-09-29 18:59:50

您需要像下面那样更改最后一个printstmt,因为您正在遍历一个列表_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()

相关问题 更多 >

    热门问题