简体   繁体   English

更改参数时如何更改全局变量

[英]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时,第一个实例可以看到if语句,但计数器仍为先前的+1。

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. 每当更改type_name时,我都想重置计数。

You're reseting the global counter but accessing the instance variable self.counter which was set at __init__ ; 您要self.counter全局counter但要访问设置为__init__的实例变量self.counter at an earlier time. 在较早的时间。 reset is only called afterwards. reset仅在之后被调用。 You should reset both in your reset method: 您应该使用自己的reset方法来重置两者:

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

On another note, I don't see why you need global here. 另一方面,我看不出您为什么需要global You can make counter and type_name class variables and reset them when you need to. 您可以创建countertype_name类变量,并在需要时重置它们。 You'll then only have to deal with one counter at a time: that on the instance or that on the class. 然后,您一次只需要处理一个counter :实例或类上的counter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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