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")
noname7619
  • 3,370
  • 3
  • 21
  • 26
  • 3
    You could just check `if cls._config is None`, or look into metaclasses, or just do `class A: _config = some_config_parser()`. – jonrsharpe Apr 20 '16 at 08:14

2 Answers2

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()
cdarke
  • 42,728
  • 8
  • 80
  • 84
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

Byte Commander
  • 6,506
  • 6
  • 44
  • 71
  • 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? – noname7619 Apr 20 '16 at 09:13
  • 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 http://stackoverflow.com/q/12487549/4464570 – Byte Commander Apr 20 '16 at 09:25