Search code examples
pythonclassstatic-methodsstatic-variablesclass-names

Use class name to access static variables


Is there a way to access a class variable without explicitly using the class name, in case I decided to change the name of the class later on?

Something like this

static_variable = 'stuff'

className = CLASS

def method (self):
    className.static_variable

Is this possible in a simple way?

Answer

self.static_variable or __class__.static_variable


Solution

  • Don't forget to read the comments.


    For anybody looking for an answer to this, disregarding for the moment whether mixing static and instance variables is a good idea.

    There are two simple ways to approach this.

    First way

    class MyClass():
        static_variable = 'VARIABLE'
    
        def __init__(self):
            self.instanceVariable = 'test'
    
        def access_static(self):
            print(__class__.static_variable)
    

    Second way

    class MyClass():
        static_variable = 'VARIABLE'
    
        def __init__(self):
            self.instanceVariable = 'test'
    
        def access_static(self):
            print(self.static_variable)
    

    An instance variable can be accessed using class.static_variable, or using self.static_variable as long as an instance variable hasn't been defined for self.static_variable somewhere in the code.

    Using self would make it ambiguous as to whether you are accessing a static variable or instance variable though, so my preferred way of doing it would be to simply prepend static_variable with class instead of ClassName.static_variable