简体   繁体   中英

Python Accessing Dict That Has Defualt Values That Have Been Updated

So I have this class:

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")

And in another class I have this executing

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"

So if I input nothing each time, it will result in a blank user input, and give the default values. But if I put an input, then it will change the herodict values to what I customize. My problem is, if I try and access those updated values in Someclass it only gives me the default values instead of the new ones. How do I go about accessing the updated values?

The main issue with your class is that you are creating a new object within heromake instead of using the existing one. You can fix this by replacing h with self (so that each time you are calling setHeroDicts on the object):

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

The first argument to a method is always set to the instance itself, so if you want to interact with the instance or mutate it, you need to use it directly. When you do h = hero() in your original code, you create a whole new hero object, manipulate it and then it disappears when control passes back to your function.

A few other notes: you should name your classes with CamelCase, so it's easier to tell they are classes (eg, you should really have class Hero ) and in python 2, you need to make your classes descend from object (so class Hero(object) ). Finally, you are duplicating nearly the entire point of having classes with your herodict , you should consider accessing the attributes of the object directly, instead of having the intermediary herodict (eg, instead of doing h.herodict["Class"] you could do h.prof directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM