I have a question regarding accessing class variable from the class. Which way is preferred? Why Version 1 works? name isn't instance variable, how it can be accessed using .self?
Version 1:
class Base:
def get_name(self): return self.name
class Child_1(Base):
name = 'Child 1 name'
child = Child_1()
print(child.get_name())
Version 2:
class Base:
@classmethod
def get_name(cls): return cls.name
class Child_1(Base):
name = 'Child 1 name'
child = Child_1()
print(child.get_name())
Motivation behind this, is defining name once for all instances to save space.
nameit will return that.selfworks just fine. If there is no instance attribute of the same name, you get the class attribute. But assigning to it will hide the class attribute with a new instance attribute of the same name. Which is probably not what you wanted.