python中import list,dictionary常量在class实例化时遇到的坑

事情大概是这样的:
我定义了一个dict
a = {'a':0,'b':1,'c':2}
在另外一个python文件中import了上面的a
from test import a
class test1:
def add(self):
b = '3'
a.update({'d': b})
print(a)

def add1(self):
b = 4
a.update({'e':b})
print(a)

if __name__ == '__main__':
tst = test1()
tst.add()
tst.add1()
我预想的是add和add1是分别将各自里面的key,value添加到a这个dict中去。结果,运行得到的却是:

{'a': 0, 'b': 1, 'c': 2, 'd': '3'}

{'a': 0, 'b': 1, 'c': 2, 'd': '3', 'e': 4}

解决方案一:

from test import a
class test1:
def add(self):
b = '3'
     s = a.copy()
s.update({'d': b})
print(s)

def add1(self):
b = 4
     s = a.copy()
s.update({'e':b})
print(s)

if __name__ == '__main__':
tst = test1()
tst.add()
tst.add1()
将import的dict进行复制,而不是直接在dict上进行操作(list同理)

解决方案二:
def getA():
  return {'a':0,'b':1,'c':2}

from test import getA()
class test1:
def add(self):
b = '3'
     s = getA()
s.update({'d': b})
print(s)

def add1(self):
b = 4
     s = get()
s.update({'e':b})
print(s)

if __name__ == '__main__':
tst = test1()
tst.add()
tst.add1()
这个就是每次赋值的时候都调方法动态获取,避免在同一个实例化中传递了。
原文地址:https://www.cnblogs.com/zoulifeng2017/p/13819252.html