将变量从类传递给类

时间:2014-05-09 18:40:25

标签: python class variables dictionary game-engine

我试图在python中创建一个游戏保存文件,使用如下所示的dict:

       user = {
        'Name': 'craig',
        'HP': 100,
        'ATK': 20,
        'DEF' : 10,
        'GOLD' : 300,
        'INV' : [0, pants],
        'GEAR' : [0, axe],
        'CityLevel' : 0,
        'BadAns': 0,
        }

我将它传递给类,就像在excercise 43 of learn python the hard way

中一样

中的代码

" ############

代码

#######"

有效,但替换所有这些      name = temp 没有通过用户'变量和返回一样,就像当前代码一样。

class User():
  def enter(self, user):

    def writing(self, user):
        pickle.dump(user, open('users.pic', 'a'))

    print "Is this your first time playing?"
    answer = prompt()

    if answer == 'yes':
        print "Welcome to the Game!"
        print "What do you want to name your character?"
        user['Name'] = prompt()
        writing(self, user)
        print "You'll start out in the city, at the city entrance, Good luck!"
        gamesupport.print_attributes(player)
        return 'City Entrance'
    elif answer == 'no':
        print "what is your character's name?"
        charname = prompt()
        temp = pickle.load(open('users.pic'))
        ######################################
        user['Name'] = temp['Name']
        user['GOLD'] = temp['GOLD']
        user['HP'] = temp['HP']
        user['ATK'] = temp['ATK']
        user['DEF'] = temp['DEF']
        user['GEAR'] = temp['GEAR']
        user['CityLevel'] = temp['CityLevel']
                    ############################################
        print user
        return 'City Entrance'
    else:
        print "we're screwed"

打印用户'按预期工作,即使我只使用' user = temp'也能正确打印所有内容,但用户变量不会被保存并传递给游戏的其余部分

为什么会这样,我该如何解决?必须逐行键入每个属性并不好,因为那时我无法向用户'添加任何内容。并让它再次保存和加载。

1 个答案:

答案 0 :(得分:0)

这与Python引用对象的方式有关。看一下这个例子:

>>> test = {}
>>> test2 = test
>>> test2 is test
True
>>> def runTest(test):
...     print test is test2
...     test = {}
...     print test is test2
... 
>>> runTest(test)
True
False

如您所见,在runTest函数中,如果使用test = ...,则变量引用新字典。解决此问题的方法是使用update方法。这会将源字典中的所有值复制到目标字典中:

>>> source = {'a':'b', 'c':'d'}
>>> target = {'a':'g', 'b':'h'}
>>> target.update(source)
>>> print target
{'a':'b', 'b':'h', 'c':'d'}