I’m having a problem understanding why a class object I created fails to return back an randomly chosen item from a list. I know the fault is with me failing to understand something basic in how the value is passed. I’m still new to learning Python and this is only my second application. My ultimate goal is to create an object of class Weapons() called armed that has a feature called weapon. I want to be able to create ‘armed.weapon’ which is a weapon randomly chosen from a list and then later assigned to a variable in another class object, i.e. ‘hero_weapon = armed.weapon’. Here’s the example I wrote trying to create ‘armed.weapon’ and then print the value. What is the flaw in my logic here? Why do I encounter “NameError: global name ‘weapon’ is not defined”?
from random import randint
class Weapons(object):
def __init__(self, weapon = ''):
self.weapon = weapon
self.weapons_list = [
'Flame Blade',
'Ice Flail',
'Lightning Mace'
]
def choices(self):
self.weapon = self.weapons_list[randint(0, 2)]
self.weapon = weapon
return weapon
armed = Weapons()
armed.choices()
print armed.weapon
In your
choices()method:weaponis not declared, perhaps you wanted to do something like this:Or simply: