Reputation: 179
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 increment 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.
Upvotes: 0
Views: 40
Reputation: 78536
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.
Upvotes: 1