Search code examples
pythonclassstatic-variables

Initialize static class atributes in python


I have the following class

class Test:
    x = None  # this is a static variable common to all object created from this class

    @classmethod
    def initializeX(cls):
        cls.x = 5

Note that x in practice is an object that needs to be common to all objects created from this class and I can not write e.g x = 5 so I need a function to initialize it. So how can I call the function that initializes x only once and not for every object created? Also is it generally good practice in python to skip x = None and define x directly in initializeX(cls)?


Solution

  • In the class constructor you could write an if check to see if the class attribute has been created already

    if Test.x is None:
      # Do initialization