If there are multiple classes that inherit from the parent class that has class variables Note that the behavior when the child class accesses the class variable was suspicious.
Conclusion (?):
--Mutable class variables are likely to be shared even in the inherited child class. --Overwrite the same variable in the child class if you want to manage them separately
#Parent class
class AbstClass:
class_number = 0
dict_number = {'class': 0}
#Child class 1
class Class1(AbstClass):
def __init__(self):
self.class_number = 1
self.dict_number['class'] = 1
#Child class 2
class Class2(AbstClass):
def __init__(self):
self.class_number = 2
self.dict_number['class'] = 2
obj1 = Class1()
print(obj1.class_number, obj1.dict_number['class']) # 1,1 ← Understand
obj2 = Class2()
print(obj2.class_number, obj2.dict_number['class']) # 2,2 ← Understand
print(obj1.class_number, obj1.dict_number['class']) # 1, 2 ←!?
It is easy to understand if "two child classes are accessing the class variables of the same parent class", In the above example
--class_number
is managed separately by two classes
--dict_number
is shared by two classes → Overwrites dict_numer rewritten in Class1 when Class2 () is done
It has become.
Is mutable / immutable involved? I guess. In other words
--mutable class variables (dict_number
above): shared by child classes
--immutable class variables (class_number
above): managed separately in child classes
In fact, if you define a tuple of class_number_tuple = (0,)
in AbstClass,
The same behavior as class_number
was confirmed.
(* Int is immutable. Reference:
[GAMMASOFT: Python built-in data type classification table (mutable, etc.)]
(https://gammasoft.jp/blog/python-built-in-types/))
Redefine class variables in child classes:
class Class1(AbstClass):
class_number = 0
dict_kv = {'class': 0}
class Class2(AbstClass):
class_number = 0
dict_kv = {'class': 0}
And, in each instance, the class variable of each class is prioritized = it will be managed separately.
However, if you want, I want you to automatically raise an exception as a language.
――In fact, when I put a list in the key of the dictionary, I get angry with unhashable
--If it is possible to specify "class variables to be shared" and "class variables to be overwritten by child classes" like @abstractmethod
of ABC ...
As a current measure,
--Do not define class variables in abstract classes that are supposed to be inherited (as mentioned above, it is safer to redefine in child classes, so it is simply a waste of lines) --Use delegation instead of inheritance when you need to access class variables of other classes (ideal) --Read the source code of the inherited class even at the beginning (reality)
Is it about ... I would appreciate it if you could tell me any good measures.
Recommended Posts