acollection_
acollection_

Reputation: 191

Using attributes from one class inside of another one

I'm working on a small fighting game as a learning experience and right now I'm working on implementing a store where you can buy weapons.
I decided to use a class for the store and have everything that you can do in it as a class method. But I'm unsure how to get all the data from my Weapon class and use it in the Store class. It's not pretty but here's what I have so far:

Sorry for misspelling tier.

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()

I can't get the show_weapon function to print the _id for the weapon. All I can do is get it to print the raw object data.

Edit: I've figured out how to display the _id of the weapon when I'm passing the list w_teir_1 through the show_weapons method. But when I attempt to push w_teir_2 through, I get this error: AttributeError: 'list' object has no attribute '_id'

Upvotes: 0

Views: 60

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174786

You need to change the last print stmt like below, since you're iterating over a list. _id attribute exists only for the elements which exists inside that list.

print str(i), '.', weapon._id

or

print str(i) +  '.' +  weapon._id

Update:

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()

Upvotes: 1

Related Questions