2

There is a similar question, but it doesn't explicitly answer my question: is there a way to have an init/constructor function which will be automatically called just ONCE among all class instances so that to initialize class variables?

class A:
  _config = None
#load the config once for all instances
  @classmethod
  def contstructor(cls):
    cls._config = configparser.ConfigParser()
    cls._config.read("config_for_A.ini")
1
  • 3
    You could just check if cls._config is None, or look into metaclasses, or just do class A: _config = some_config_parser(). Commented Apr 20, 2016 at 8:14

2 Answers 2

3

This is called the "Orcish Maneuver". It does assume that the "cache" can be evaluated as a Boolean.

class A:
  _config = False
#load the config once for all instances
  @classmethod
  def contstructor(cls):
    cls._config = configparser.ConfigParser()
    cls._config.read("config_for_A.ini")

  def __init__(self):
      self._config = self._config or self.contstructor()

hay = A()
bee = A()
sea = A()
Sign up to request clarification or add additional context in comments.

Comments

3

There are no magic methods for class constructors, but Python executes all code inside a class definition that does not belong to methods when parsing the class. So you can either perform your actions and assignments there directly or call a custom method of your class from there that serves as class constructor.

print("Now defining class 'A'...")

class A:

    # define any initialization method here, name is irrelevant:
    def __my_class_constructor():  
        print("--> class initialized!")

    # this is the normal constructor, just to compare:
    def __init__(self):
        print("--> instance created!")

    # do whatever you want to initialize the class (e.g. call our method from above)
    __my_class_constructor()  

print("Now creating an instance object 'a' of class 'A'...")

a = A()

The output will be:

Now defining class 'A'...
--> class initialized!
Now creating an instance object 'a' of class 'A'...
--> instance created!

See this code running on ideone.com

2 Comments

This looks exactly what I meant, but I doubt is this fine from a style point of view? Will it be executed only once when included in many modules?
A module gets only imported once in a Python process. Subsequent import calls will return the cached module without loading and evaluating it again, so the class will also not get parsed twice. See stackoverflow.com/q/12487549/4464570

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.