When explaining the concept of class variables and instance variables in Python
For variables that are defined as class variables but not as instance variables,
Isn't it strange that you can access with the notation of instance variables self. Class variable name
? I noticed.
→ I wrote a simple code and confirmed the behavior of self. Class variable
.
In Python, when you refer to self.variable name
,
To avoid congestion, it is safer to write class name.class variable name
when referencing a class variable in an instance.
self.py
class Hoge:
id = 0
@classmethod
def dump_class(cls):
print("Class variables: ", cls.id)
def construct(self, id):
self.id = id
def dump_instance(self):
print("Instance variables: ", self.id)
if __name__ == "__main__":
Hoge.dump_class() # -> 0
hoge_instance = Hoge()
hoge_instance.dump_instance() # -> 0,If no instance variable is defined, the class variable with the same name will be referenced.
hoge_instance.dump_class() # -> 0
hoge_instance.construct(id=10) #Define instance variables
hoge_instance.dump_instance() # -> 10,Instance variable reference takes precedence
hoge_instance.dump_class() # -> 0
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. Python class variables and instance variables | UX MILK
Recommended Posts