KocT9H
KocT9H

Reputation: 349

Using class method to access class variable within a class

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.

Upvotes: 0

Views: 59

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 114088

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

Upvotes: 1

Related Questions