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?

2
  • 1
    Your counter variable is a class variable instead of an instance variable. You would access instance variables using self. docs.python.org/2/tutorial/… Commented Mar 21, 2019 at 20:14
  • 2
    your code doesn't work: increment isn't a class method and counter should be self.counter Commented Mar 21, 2019 at 20:15

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

I think we can call that a classic duplicate and avoid answering this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.