猿问

全局变量不更新?

import datetime as DT

import calendar

def getMonthRanges(startDate, endDate):

    while startDate <= endDate:

        year, month = startDate.year, startDate.month

        weekday, day = calendar.monthrange(year, month)

        end = min(DT.date(year, month, day), endDate)

        yield (startDate, end)

        startDate = end+DT.timedelta(days=1)


ranges = [map(str, interval) 

          for interval in getMonthRanges(DT.date(2011,9,11), DT.date(2013,4,24))]

print(ranges)

产量


[['2011-09-11', '2011-09-30'], ['2011-10-01', '2011-10-31'], ['2011-11-01', '2011-11-30'], ['2011-12-01', '2011-12-31'], ['2012-01-01', '2012-01-31'], ['2012-02-01', '2012-02-29'], ['2012-03-01', '2012-03-31'], ['2012-04-01', '2012-04-30'], ['2012-05-01', '2012-05-31'], ['2012-06-01', '2012-06-30'], ['2012-07-01', '2012-07-31'], ['2012-08-01', '2012-08-31'], ['2012-09-01', '2012-09-30'], ['2012-10-01', '2012-10-31'], ['2012-11-01', '2012-11-30'], ['2012-12-01', '2012-12-31'], ['2013-01-01', '2013-01-31'], ['2013-02-01', '2013-02-28'], ['2013-03-01', '2013-03-31'], ['2013-04-01', '2013-04-24']]

分享全局变量不会更新,但是我将其导入到正在更新的解释器中。


请帮我如何更新字典 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


狐的传说
浏览 242回答 1
1回答

弑天下

您的全局变量正在更新。提取部分代码:class Lc:&nbsp; &nbsp; d={50:8,100:6,200:4,500:3,1000:2,2000:1}&nbsp; &nbsp; he=['container_size_in_ltrs','qty']&nbsp; &nbsp; def add_inv(self,k,v):&nbsp; &nbsp; &nbsp; &nbsp; d=self.d&nbsp; &nbsp; &nbsp; &nbsp; for i,j in d.items():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if k==i:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d[k]=d[k]+v&nbsp; &nbsp; &nbsp; &nbsp; print d&nbsp; &nbsp; &nbsp; &nbsp; return dz=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.dprint "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这种卑鄙的方式宣布其为全球性。
随时随地看视频慕课网APP

相关分类

Python
我要回答