通过函数变量访问类变量

时间:2017-02-02 14:34:41

标签: python class variables

我正在玩Python 3并组建一个RPG风格的系统,但我正在努力使用OOP,因为我之前并未真正在python中使用它。

我特意挣扎着以下功能:

HKEY_CURRENT_USER\SOFTWARE\ej-technologies\install4j\RebootCheckFile
HKEY_LOCAL_MACHINE\SOFTWARE\ej-technologies\install4j\RebootCheckFile

这应该从下面开始,将playerchar.strength设置为选定的数量:

def choosestat(statname, max, min):
    # Takes the name of the stat
    # as mentioned in the Player/Character class and
    # a min/max value for the length. Allows the player
    # to set their stats for the char.
    print("Your stat choices are: " + str(stats))
    choice = int(input("Please select a strength score ("+min+":"+max+")\n"))
    if type(choice) == int and choice < (max+1) and choice > (min-1):
        self.statname = stats[choice-1]
        stats.pop(choice-1)
    else:    
        print("Please select a valid option.\n")

然而,当我运行代码时,我只是得到:

class Character(object):
# A Class for ALL characters - player, enemy etc.
def __init__(self, name, hp, armor, damage, strength,
             intelligence, wisdom, dexterity, constitution, charisma,
             inventory, profession):
    self.name = name
    self.hp = hp
    self.armor = armor
    self.damage = damage
    self.strength = strength
    self.intelligence = intelligence
    self.wisdom = wisdom
    self.dexterity = dexterity
    self.constitution = constitution
    self.charisma = charisma
    self.inventory = inventory
    self.profession = profession


class Player(Character):
# A class for the Player character only.
# We will use a few parameters to set initial variables
def __init__(self):
    super().__init__(name="", hp=10, armor=10, damage=10, strength=7,
                     intelligence=7, wisdom=7, dexterity=7, constitution=7,
                     charisma=7, inventory=[], profession="")
maxhp = 10
level = 1
exp = 0

完整的代码在这里:

Traceback (most recent call last):
 File "main.py", line 122, in <module>
menu()
 File "main.py", line 53, in menu
gameloop()
File "main.py", line 73, in gameloop
statchoice()
File "main.py", line 108, in statchoice
choosestat(strength, 6, 1)
NameError: name 'strength' is not defined

2 个答案:

答案 0 :(得分:0)

您可以使用setattr()

choosestat('strength', 6, 1)

def choosestat(statname, max, min):
    print("Your stat choices are: " + str(stats))
    choice = int(input("Please select a strength score ("+min+":"+max+")\n"))
    if type(choice) == int and choice < (max+1) and choice > (min-1):
        setattr(self, statname, stats[choice-1]
        stats.pop(choice-1)
    else:
        print("Please select a valid option.\n")

将要更改的字段名称字符串传递给setattr()或在这种情况下通过choosestat()传递是非常重要。

答案 1 :(得分:0)

如果您致电choosestat,您希望班级内有self.*something*个功能。现在不是。如果您在Character类中移动它并向其添加self参数。然后,您可以访问该类的成员。目前在statchoice中,未定义强度。您可以尝试传入字符串“strength”并在choosestat(Character的成员)内部使用dict将字符串映射到其成员计数器部分: {"strength" : self.strength, "intelligence" : self.intelligence}等等。另外,我不认为你的stats数组是全局的,所以你要么必须使它成为全局数组,要么以某种方式成为类的成员并重新编写其他函数。