<span style="font-family:Courier New;">__author__ = 'Lxp'</span>
<span style="font-family:Courier New;">自定义函数:
a = {1: 'a', 'ps': {'p1': {11: 'aaa', 22: 'aab', 33: 2}, 'p2': {11: 'bba', 22: 'bbb', 33: 10000}}}</span>
<span style="font-family:Courier New;">
def myfunc(pinfo):
print '------'
print pinfo
pinfo[33]=pinfo[33]+0.0088
print pinfo
pinfo[33]-= 0.0044
print pinfo
print '------'
myp=P(a)
print myp.ps
myfunc(myp.ps['p1'])
print myp.ps</span>
<span style="font-family:Courier New;">
</span>
<span style="font-family:Courier New;">
</span>
<span style="font-family:Courier New;">输出结果:</span>
<span style="font-family:Courier New;">{'p2': {33: 10000, 11: 'bba', 22: 'bbb'}, 'p1': {33: 2, 11: 'aaa', 22: 'aab'}}
------
{33: 2, 11: 'aaa', 22: 'aab'}
{33: 2.0088, 11: 'aaa', 22: 'aab'}
{33: 2.0044, 11: 'aaa', 22: 'aab'}
------
{'p2': {33: 10000, 11: 'bba', 22: 'bbb'}, 'p1': {33: <span style="color:#ff0000;">2.0044</span>, 11: 'aaa', 22: 'aab'}}</span>
结论:当字典作为参数传入函数时,函数里面的修改会影响到原来的字典
类中使用另一个变量代替字典key的结构
<span style="font-family:Courier New;">class P:
def __init__(self, A):
self.fir=A[1]
self.ps=A['ps']
#self.pInfoSet = []</span>
<span style="font-family:Courier New;">
def change(self):
for p in self.ps:
certainP=self.ps[p]
certainP['name']='x'
certainP[33]+=0.99
certainP[33]= certainP[33] + 0.44
certainP[11]=certainP[11]+'xy'
certainP[11]+='z'
print myp.ps</span>
<span style="font-family:Courier New;"></span><pre name="code" class="html"><span style="font-family:Courier New;">myp=P(a)
print myp.ps
myp.change()
print myp.ps</span>
<span style="font-family:Courier New;">
</span>
输出结果:
<span style="font-family:Courier New;"></span><pre name="code" class="python"><span style="font-family:Courier New;"> {'p2': {33: 10000, 11: 'bba', 22: 'bbb'}, 'p1': {33: 2, 11: 'aaa', 22: 'aab'}}
{'p2': {33: 10001.43, 11: 'bbaxyz', 'name': 'x', 22: 'bbb'}, 'p1': {33: 3.43, 11: 'aaaxyz', 'name': 'x', 22: 'aab'}}
</span>
结论:若b是一个字典结构,令a=b, a中的变动会导致b中发生变动