twisted loopingcall访问类变量

时间:2012-01-06 20:23:32

标签: python twisted

我有以下示例

class Intake:
    def __init__(self):

        #
        # aggregate dict to store all the counters
        #
        self.counters = {}

        #
        # start a looping call to run reach minute
        #
        self.lc = task.LoopingCall(self.aggregate, self.counters)
        self.lc.start(60)


    def aggregate(self, counters):
        print counters

所以这很好..但在我的聚合函数中我需要清除self.counters dict。我有问题这样做..

我想做点什么

    def aggregate(self, counters):
        print counters

        self.counters = {}

如果我在该函数中引用self.counters,我会得到

exceptions.AttributeError: Intake instance has no attribute 'counters'

1 个答案:

答案 0 :(得分:3)

包含问题的可运行示例是个好主意,如果我尝试你所描述的它可以正常工作。

from twisted.internet import task

class Intake:
    def __init__(self):

        #
        # aggregate dict to store all the counters
        #
        self.counters = {}
        self.count = 0
        #
        # start a looping call to run reach minute
        #
        self.lc = task.LoopingCall(self.aggregate, self.counters)
        self.lc.start(1)


    def aggregate(self, counters):
        print '%d, %r, %r' % (self.count, counters, self.counters)
        self.count += 1
        self.counters = {}

if __name__ == "__main__":
    from twisted.internet import reactor
    r = Intake()
    reactor.run()