如何在其中一个条件发生变化时重置计数器(全局变量)

时间:2017-06-08 05:57:44

标签: python class

当其中一个条件发生变化时,如何重置计数器(全局变量)。基本上,将计数器增加1直到“type_name”为“Bar”,如果它改变为其他东西将计数器设置为0.如何实现多个type_names'。谢谢。

type_name = "bar"
counter = 0

class Foo(object):
    """ 
    if type is different in the argument, reset counter to 0.
    Otherwise, increment the counter by 1.
    """

    def __init__(self, type_name):
        self.type_name = type_name
        self.counter = counter
        self.reset()

    def increament_counter(self):
        self.counter +=1

    def reset(self):
        if self.type_name != type_name:
            self.counter = 0


b = Foo("bar")
b.increament_counter()
b.increament_counter()
print b.counter


print "==============================="
c = Foo("taste")
c.reset()
print c.counter
c.increament_counter()
print c.counter


print "--------------------------"
d = Foo("bar")
d.increament_counter()
d.increament_counter()
print d.counter

print "--------------------------"
e = Foo("car")
e.increament_counter()
e.increament_counter()
print e.counter

2 个答案:

答案 0 :(得分:3)

你在这里做的是你不是在修改全局变量,而是在修改班级中的计数器(self.counter)
你需要做的是,在你的重置功能中,改变全局计数,而不是那个类对象属性中的全局计数。

def reset(self):
    global counter
    if self.type_name != type_name:
        counter = 0

答案 1 :(得分:0)

谢谢。由于篇幅限制,我在这里添加了一个更新的代码,还有一个用例。

type_name = "bar"
counter = 1

class Foo(object):
    """ 
    if type is different in the argument, reset counter to 0.
    Otherwise increament counter by 1.
    """

    def __init__(self, type_name):
        self.type_name = type_name
        self.counter = counter
        self.reset()


    def reset(self):
        global counter
        if self.type_name != type_name:
            counter = 1
        else:
            counter += 1

c = Foo("taste")
print c.counter

print "--------------------------"
d = Foo("bar")
print d.counter

print "--------------------------"
e = Foo("taste")
print e.counter

print "--------------------------"
new_instances = []
for i in range(0, 10):
    new_instances.append(Foo("bar"))
print new_instances
print new_instances[0].counter
print new_instances[8].counter