I confused a class variable with an instance variable in Python, so it didn't work as I expected. Make a note for reference.
It seems to be a common mistake, and there are articles dealing with the same topic.
The points are summarized in this comment.
The behavior of python is that when referring to self.odds, it first refers to the instance variable, otherwise it refers to the class variable.
Another article also calls attention.
When accessing class variables, you should avoid accessing them like "instance.class variables" or "self.class variables" unless you have a specific reason to do so. In Python, you can create an instance variable from an instance object, and you may unintentionally hide a class variable with an instance variable.
Let's see this with a simple example.
Since I can access class variables via self
, I misunderstood that I defined an instance variable.
class Test:
a = []
def append(self, value):
self.a.append(value)
def clear(self):
self.a = []
t1 = Test()
t1.append(123)
print(t1.a)
t1.clear()
print(t1.a)
Execution result
[123]
[]
Looking at this, I thought that the value was cleared. In reality, the class variable is just obscured by the instance variable of the same name.
If you create another instance, you will see the class variable with 123
added.
t2 = Test()
print(t2.a)
Execution result
[123]
What I really fell in love with was a program that called clear
many times. Although I noticed that the behavior was strange, I did not pay attention to the state immediately after the instance was created, and the investigation of the cause was delayed.
Let's initialize the instance variable with the constructor.
class Test:
def __init__(self):
self.a = []
Recommended Posts