0

I have been using the standard Counter object to count things in my code. I recently restructured it and started getting weird counts. I've narrowed it down and what happens is that the same Counter object gets called even though I would think they would be different.

from collections import Counter

class ABase:
    counter = 0
    counterObj = Counter()

    def doCount(self):
        self.counter += 1
        tmpCounter = Counter({"blah"})
        self.counterObj.update(tmpCounter)

    def printCount(self):
        print(f"Raw count: {self.counter}  CounterObject: {self.counterObj}")


b1 = ABase()
b1.doCount()
b1.printCount()

b2 = ABase()
b2.doCount()
b2.printCount()

I would think that it would print 1 for both the integer counter and the Counter object, but here is what it produces:

Raw count: 1  CounterObject: Counter({'blah': 1})
Raw count: 1  CounterObject: Counter({'blah': 2})

What? I'm creating a new Counter object for each instance of the class, so why is the value for Counter 2? Is Counter using a global hash somewhere?

C Dorman
  • 551
  • 5
  • 12
  • 1
    *"I'm creating a new Counter object for each instance of the class"* - no, you aren't. – jonrsharpe May 23 '20 at 13:17
  • Well actually you are, but it’s not the one that is printed. – mkrieger1 May 23 '20 at 13:19
  • Well, I guess that's what I get for coming from a Java background where class variables need static. Thank you for the help. – C Dorman May 23 '20 at 13:22
  • 1
    The crucial difference here is that `self.counter += 1` creates an instance variable the first time it’s called, which shadows the class variable but leaves it unchanged, while `counterObj.update` mutates the class variable. – mkrieger1 May 23 '20 at 13:22
  • See https://stackoverflow.com/questions/32527535/changing-a-class-attribute-within-init – mkrieger1 May 23 '20 at 13:25

0 Answers0