Mochamethod
Mochamethod

Reputation: 276

How to use class that is returned through a function?

If I have a class that generates items for a text-based RPG like so -- keep in mind this is a simplified version of the code I use:

from random import choice, randint

class Weapon(object):
    def __init__(self, name, value, damage):
        self.name = name
        self.value = value
        self.damage = damage


class CreateWeapon(object):
    def __init__(self):
        self.prefix = ['rusty', 'polished', 'blessed']
        self.weaponType = ['long sword', 'halberd', 'axe']

    def generate(self):
        weaponName = choice(self.prefix) + ' ' + choice(self.weaponType)
        print weaponName

        if weaponName[0] == 'r':
            weaponDamage = randint(5, 20)

        else:
            weaponDamage = randint(20, 40)

        weaponValue = randint(1, weaponDamage * 3)
        return Weapon(weaponName, weaponValue, weaponDamage)

My question being: how can I manipulate the Weapon object I create through the generate() method of the CreateWeapon class? For instance, if I have a player class with an inventory attribute:

class Player(object):
    def __init__(self):
        self.inventory = {'weapons': []}

    def addWeaponDrop(self):
        createweapon = CreateWeapon()
        createweapon.generate()
        print 'What do?' 
        """self.inventory['weapons'].append()"""

player = Player()

... and I call the player method addWeaponDrop() to create a randomized weapon, how do I add that weapon object to the player's inventory? Thanks for any help.

Upvotes: 0

Views: 54

Answers (2)

Lewis Fogden
Lewis Fogden

Reputation: 524

your generate function returns a weapon. You just need to assign it (or store it directly).

e.g.

generated_weapon = CreateWeapon.generate()
self.inventory['weapons'].append(generated_weapon)

or to store it directly

self.inventory['weapons'].append(CreateWeapon.generate())

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599460

generate() returns a Weapon instance, which you can simply append to your inventory.

weapon = createweapon.generate()
self.inventory['weapons'].append(weapon)

I must say though, I don't think CreateWeapon should be a class. Classes are for things - ie Weapons themselves; generate should be a classmethod on Weapon.

Upvotes: 3

Related Questions