0

I have a class and created its instances a and b. I think both instances points same address.

For example,

class Foo:
    counter = 0
    def increment():
        counter += 1

a = Foo()
b = Foo()
for i in range(10):
    a.increment()
    b.increment()
    aa = a.counter
    bb = b.counter
    print(aa)
    print(bb)

I expected that aa = 10 and bb = 10. However bb = 20 at this point. What am I missing?

divibisan
  • 11,659
  • 11
  • 40
  • 58
jayko03
  • 2,329
  • 7
  • 28
  • 51
  • 1
    Your counter variable is a class variable instead of an instance variable. You would access instance variables using self. https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables – havanagrawal Mar 21 '19 at 20:14
  • 2
    your code doesn't work: `increment` isn't a class method and `counter` should be `self.counter` – Jean-François Fabre Mar 21 '19 at 20:15

1 Answers1

1

If you intend to make the counter specific to each instance you should make it an instance variable and initialize it in the __init__ method instead:

class Foo:
    def __init__(self):
        self.counter = 0
    def increment(self):
        self.counter += 1
blhsing
  • 91,368
  • 6
  • 71
  • 106