Python访问具有已更新的default值的Dict

2024-03-29 14:45:59 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一节课:

class hero():

    def __init__(self, name="Jimmy", prof="Warrior", weapon="Sword"):
        """Constructor for hero"""
        self.name = name
        self.prof = prof
        self.weapon = weapon
        self.herodict = {
            "Name": self.name,
            "Class": self.prof,
            "Weapon": self.weapon
        }
        self.herotext = {
            "Welcome": "Greetings, hero. What is thine name? ",
            "AskClass": "A fine name, {Name}. What is your class? ",
            "AskWeapon": "A {Class}, hmm? What shalt thy weapon be? ",
        }

    def setHeroDicts(self, textkey, herokey):
        n = raw_input(self.herotext[textkey].format(**self.herodict))

        if n == "":
            n = self.herodict[herokey]

        self.herodict[herokey] = n
        #print self.herodict[herokey]

    def heroMake(self):
        h = hero()
        h.setHeroDicts("Welcome", "Name")
        h.setHeroDicts("AskClass", "Class")
        h.setHeroDicts("AskWeapon", "Weapon")

在另一节课上我有一个

def Someclass(self):
    h = hero()
    print h.herodict["Class"]
    h.heroMake()
    print h.getClass()

    if "Mage" in h.herodict["Class"]:
        print "OMG MAGE"
    elif "Warrior" in h.herodict["Class"]:
        print "Warrior!"
    else:
        print "NONE"

因此,如果每次都不输入任何内容,将导致用户输入为空,并给出默认值。但是如果我输入一个值,那么它会将herodict值更改为我自定义的值。我的问题是,如果我尝试访问Someclass中更新的值,它只会给我默认值,而不是新值。如何访问更新的值?你知道吗


Tags: nameselfdefwhatclassprintheroweapon
1条回答
网友
1楼 · 发布于 2024-03-29 14:45:59

类的主要问题是在heromake中创建新对象,而不是使用现有对象。您可以通过将h替换为self来解决此问题(因此每次调用对象上的setHeroDicts):

def heromake(self):
    self.setHeroDicts("Welcome", "Name")
    self.setHeroDicts("AskClass", "Class")
    self.setHeroDicts("AskWeapon", "Weapon")

方法的第一个参数总是设置为实例本身,因此如果要与实例交互或对其进行修改,则需要直接使用它。在原始代码中执行h = hero()时,创建一个全新的hero对象,对其进行操作,然后当控件传递回函数时,该对象消失。你知道吗

其他一些注意事项:您应该用CamelCase命名类,这样就更容易判断它们是类(例如,您真的应该有class Hero),而在python2中,您需要使类从object派生(所以class Hero(object))。最后,您几乎复制了使用herodict创建类的整个要点,您应该考虑直接访问对象的属性,而不是使用中介herodict(例如,您可以直接执行h.prof,而不是执行h.herodict["Class"])。你知道吗

相关问题 更多 >