Python 在类之间传递变量

Python 在类之间传递变量,python,class,variables,dictionary,game-engine,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, 'BadA

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

       user = {
        'Name': 'craig',
        'HP': 100,
        'ATK': 20,
        'DEF' : 10,
        'GOLD' : 300,
        'INV' : [0, pants],
        'GEAR' : [0, axe],
        'CityLevel' : 0,
        'BadAns': 0,
        }
我在课堂上传递它就像在

中的代码

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

代码在这里

#######" 有效,但用 name=temp 不会像当前代码那样将“user”变量与返回一起传递

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"
“print user”按预期工作,并正确打印所有内容,即使我只使用“user=temp”,但用户变量不会保存并传递到游戏的其余部分


这是为什么?我如何修复它?必须逐行输入每个属性是不好的,因为这样我就不能将任何内容附加到“user”中,并让它再次保存和加载。

这与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'}

看起来您本想添加一些代码,但后来忘记粘贴了。你能包括这个吗?否则,我认为这里没有足够的上下文来回答你的问题。就是这样!我已经在这方面工作了两天了,现在我试图弄清楚这是否是我一直在做的愚蠢的事情,我已经到了我认为是python如何处理变量的地步。非常感谢!值得注意的是,在全局范围内改变值而不是返回新值实际上被认为是不好的做法——在通读代码时,副作用更难理解。更好的代码版本将
返回新词典并加以利用,使程序中的数据流更加清晰。