-3

Global variable does not update but I import it to interpreter it is updating.

Please help me how to update dictionary 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
4

1 回答 1

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这种特殊的方式声明为全球性的。

于 2013-05-11T18:04:09.930 回答