'Is it possible to increment/access a class variable from inside a constructor in Python?
I want to keep track via a counter, every time a class is instantiated. I was trying to do this by incrementing a counter defined as a class variable from inside the class' consructor ala:
class Cl:
cntr = 0
def __init__(self):
cntr += 1
However, when I instantiate the class, I get an "UnboundLocalError: local variable 'cntr' referenced before assignement" I'm assuming this is because the constructor is treating it as a local variable. How do I reference the class variable from inside a method or constructor in Python 2.7?
Solution 1:[1]
You just have to call the variable through the class:
class Cl:
cntr = 0
def __init__(self):
Cl.cntr += 1 # <---Like this
print(Cl().cntr) # prints 1
print(Cl().cntr) # prints 2
print(Cl().cntr) # prints 3
Solution 2:[2]
class Foo:
n = 0
def __init__(self):
self._increment()
@classmethod
def _increment(cls):
cls.n += 1
f1 = Foo()
f2 = Foo()
>>> f1.n
2
>>> f2.n
2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric Ed Lohmar |
| Solution 2 | heemayl |
