How can a method directly access its class variables without using self?

Question:

I recently switched to Python from Java for development and is still not used to some of the implicitness of Python programming.

I have a class which I have defined some class variables, how can I access the class variables within a method in Python?

class Example:
    CONSTANT_A = "A"
    
    @staticmethod
    def mymethod():
        print(CONSTANT_A)    

The above code would give me the error message: "CONSTANT_A" is not defined" by Pylance.

I know that I can make this work using self.CONSTANT_A, but self is referring to the Object, while I am trying to directly access to the Class variable (specifically constants).


Question

How can I directly access Class variables in Python and not through the instance?

Asked By: Quan Bui

||

Answers:

In python, you cannot access the parent scope (class)’s fields from methods without self. or cls..

Consider using classmethod:

class Example:
    CONSTANT_A = "A"
    
    @classmethod
    def mymethod(cls):
        print(cls.CONSTANT_A)   

or directly accessing it like Classname.attribute:

class Example:
    CONSTANT_A = "A"
    
    @staticmethod
    def mymethod():
        print(Example.CONSTANT_A)   
Answered By: Jongwook Choi

for static method, you can access the class variable by <class_name>.<variable>.

>>> class Example:
...     CONSTANT_A = "A"
...     @staticmethod
...     def mymethod():
...         print(Example.CONSTANT_A) 
... 
>>> 
>>> x = Example.mymethod()
A # print value

Answered By: sahasrara62
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.