作成したクラス オブジェクトが、リストからランダムに選択された項目を返さない理由を理解できません。値がどのように渡されるかについて基本的なことを理解できていないことが原因であることはわかっています。私はまだ Python を学ぶのが初めてで、これは私の 2 番目のアプリケーションにすぎません。Weapons()
私の最終的な目標は、というarmed
機能を持つ というクラスのオブジェクトを作成することweapon
です。リストからランダムに選択された武器である「armed.weapon」を作成し、後で別のクラスオブジェクトの変数に割り当てられるようにしたいと考えています。つまり、「hero_weapon = armed.weapon」です。「armed.weapon」を作成して値を出力しようとして書いた例を次に示します。ここで私の論理の欠陥は何ですか? 「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