全局变量不更新?

时间:2013-05-11 17:38:10

标签: python python-2.7

全局变量不会更新,但我将其导入解释器,它正在更新。

请帮我更新字典d

import texttable

class Lc:

    d={50:8,100:6,200:4,500:3,1000:2,2000:1}
    he=['container_size_in_ltrs','qty']
    def inventory(self,g):
        d1=self.d
        if d1!=g:
            d1=g
        self.d=g
        l1=d1.keys()
        l1.sort()
        li=[]
        ls=[]
        for i in l1:
            li=[]
            li.append(i)
            li.append(d1[i])
            ls.append(li)
        table=texttable.Texttable()
        table.header(self.he)
        table.add_rows(ls,header=False)
        print table.draw()

    def add_inv(self,k,v):
        d=self.d
        for i,j in d.items():
            if k==i:
                d[k]=d[k]+v
        print d
        return d

z=Lc()

g=z.add_inv(500,2)

print z.d

1 个答案:

答案 0 :(得分:0)

您的全局变量正在更新。取一部分代码:

class Lc:

    d={50:8,100:6,200:4,500:3,1000:2,2000:1}
    he=['container_size_in_ltrs','qty']

    def add_inv(self,k,v):
        d=self.d
        for i,j in d.items():
            if k==i:
                d[k]=d[k]+v
        print d
        return d

z=Lc()
x=Lc()

print "Add 2 to 500, expect 500:5"
g=z.add_inv(500,2)
print z.d

# Notice that x.add_inv also modifies z.d
print "Add 5 to 500, expect 500:7 because x initialized d again"
h=x.add_inv(500,2)
print z.d

我明白了:

Add 2 to 500, expect 500:5
{100: 6, 200: 4, 2000: 1, 1000: 2, 50: 8, 500: 5}
{100: 6, 200: 4, 2000: 1, 1000: 2, 50: 8, 500: 5}
Add 5 to 500, expect 500:7 because x initialized d again
{100: 6, 200: 4, 2000: 1, 1000: 2, 50: 8, 500: 7}
{100: 6, 200: 4, 2000: 1, 1000: 2, 50: 8, 500: 7}

我只是希望你确实试图以这种特殊的方式宣布d为全球性。