To define a class variable in Python, you are supposed to declare the variable under the class name. That's what the official documentation says.
https://docs.python.jp/3/tutorial/classes.html#class-and-instance-variables
sample.py
class Sample:
name = 'name'
s = Sample()
s2 = Sample()
print(s.name) # 'name'
print(s2.name) # 'name'
Obviously, both are displayed as "name".
However, if you change the name like this, it will no longer be a class variable.
sample.py
s = Sample()
s2 = Sample()
s.name = 'aaaa'
print(s.name) # 'aaaa'
print(s2.name) # 'name'
When you do this, s.name
is displayed as aaaa and s2.name
is displayed as name. If it is shared by all objects, s2.name should also change to ʻaaaa`.
The answer is that strings are immutable, so if you refer to them via an object, they will automatically create an instance variable.
But when I tried Sample.name
, both changed to aaaa. It has characteristics as a class variable. Is it interpreted by reading the air depending on whether the reference source is a class or an object?
Arrays and dictionary types are mutable, so doing the following will propagate the changes and both prints will show [1,2,3,4]
. It is natural because it points to the same thing.
sample.py
class Sample:
a_list = [1,2,3]
s = Sample()
s2 = Sample()
s.a_list.append(4)
print(s.a_list) # [1,2,3,4]
print(s2.a_list) # [1,2,3,4]
I wonder if it's okay to say that immutables are automatically switched to instance variables even if they are declared under the class, and mutables are still class variables. In principle, I will share it. However, immutable data becomes an instance variable when accessed via an object.
I wonder if it has such specifications.
Recommended Posts