0

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.

3
  • Version 1 will not always get the class attribute. If there is an instance attribute name it will return that. Commented May 14, 2020 at 7:56
  • 1
    stackoverflow.com/a/25577642/6045800 TL;DR - Well, accessing a class attribute through self works 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. Commented May 14, 2020 at 7:57
  • Version 1 is typically preferred unless you have a very good reason not to (ie provide more protection against accidentally setting it) Commented May 14, 2020 at 7:58

1 Answer 1

1

self.name by default refers to cls.name

if you set it it only sets it for that instance however

self.name = "bob"

now overrides the class level name

just the same for methods as well

class Foo:
    @staticmethod
    def hello():
        print("Hi There From Foo!")
    def __init__(self):
        self.hello() #this works

 Foo.hello() # this also works
 Foo() # print from in the init
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.