简体   繁体   中英

How to change global variable when you change parameter

What am I doing wrong here? The solution works but the first instance when you change the type_name I can see it hits the if statement but the counter still goes to +1 previous count.

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, model_name):
        self.model_name = model_name
        self.counter = counter
        self.reset()


    def reset(self):
        global counter, type_name
        print self.model_name, type_name
        if type_name != self.model_name:
            print "here..."
            counter = 1
            type_name = self.model_name
            print counter
        else:
            counter += 1
        print type_name

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

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

print new_instances[5].counter
print new_instances[8].counter


print "-------------------------- taste starts here ... "
c = Foo("test")
print c.counter

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

print "--------------------------"
f = Foo("test")
print f.counter

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

print "--------------------------"
ddd = Foo("bar")

I want to reset count whenever I change the type_name.

You're reseting the global counter but accessing the instance variable self.counter which was set at __init__ ; at an earlier time. reset is only called afterwards. You should reset both in your reset method:

def reset(self):
    ...
    self.counter = counter = 1

On another note, I don't see why you need global here. You can make counter and type_name class variables and reset them when you need to. You'll then only have to deal with one counter at a time: that on the instance or that on the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM