Home > Software engineering >  How can a method directly access its class variables?
How can a method directly access its class variables?

Time:11-17

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 Object?

CodePudding user response:

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)   

CodePudding user response:

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

  • Related