I have this class in Python. (Removed the unecessary parts)
class Spillebrett:
def __init__(self, rader, kolonner):
self._rader = rader
self._kolonner = kolonner
self._generasjonsnummer = 0
I need to add 1 to _generasjonsnummer everytime i run the class. If i try _generasjonsnummer += 1 i get an error. I tried to make a def addGenerasjonsnummer() and call it in the init like so:
class Spillebrett:
def __init__(self, rader, kolonner):
self._rader = rader
self._kolonner = kolonner
self._generasjonsnummer = 0
addGenerasjonsnummer()
def addGenerasjonsnummer():
self._generasjonsnummer += 1
But i cant call on functions in the init. What i need is for this number to update to +=1 each time i start the init, how do i do this?
If your class has an attribute that is going to be incremented each time the constructor is called, then you should disassociate it with any instance to begin with. In other words, declare it as a class attribute, outside __init__
.
I'd recommend something along these lines:
In [625]: class Spillebrett:
...: ctr = 0
...: def __init__(self):
...: print(Spillebrett.ctr)
...: Spillebrett.ctr += 1
...:
In [626]: Spillebrett()
0
Out[626]: <__main__.Spillebrett at 0x10b918da0>
In [627]: Spillebrett()
1
Out[627]: <__main__.Spillebrett at 0x109f1af98>
In [628]: Spillebrett()
2
Out[628]: <__main__.Spillebrett at 0x10b918470>