Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a static constructor or static initializer in Python?

Tags:

python

Is there such a thing as a static constructor in Python?

How do I implement a static constructor in Python?

Here is my code... The __init__ doesn't fire when I call App like this. The __init__ is not a static constructor or static initializer.

App.EmailQueue.DoSomething() 

I have to call it like this, which instantiates the App class every time:

App().EmailQueue.DoSomething() 

Here is my class:

class App:     def __init__(self):         self._mailQueue = EmailQueue()      @property     def EmailQueue(self):         return self._mailQueue 

The problem with calling __init__ every time is that the App object gets recreated. My "real" App class is quite long.

like image 327
101010 Avatar asked Sep 13 '11 02:09

101010


People also ask

Can a constructor be static in Python?

As soon as the interpreter parses and starts executing all of those classes and def statements, the equivalent of a static constructor is being run. The class definitions are being executed at that point. You can put any number of statements anywhere inside the class body and they are in effect a static constructor.

Is there static class in Python?

Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class.

What is a static method in Python?

What is a static method? Static methods, much like class methods, are methods that are bound to a class rather than its object. They do not require a class instance creation. So, they are not dependent on the state of the object.

Is Init constructor in Python?

"__init__" is a reserved method in python classes. It is known as a constructor in OOP concepts. This method called when an object is created from the class and it allows the class to initialize the attributes of a class.


1 Answers

There's a fundamental difference between static and dynamic languages that isn't always apparent at first.

In a static language, the class is defined at compile time and everything is all nice and set in concrete before the program ever runs.

In a dynamic language, the class is actually defined at runtime. As soon as the interpreter parses and starts executing all of those classes and def statements, the equivalent of a static constructor is being run. The class definitions are being executed at that point.

You can put any number of statements anywhere inside the class body and they are in effect a static constructor. If you want, you can place them all in a function that doesn't take self as a parameter, and call that function at the end of the class.

like image 101
Sam Corder Avatar answered Sep 18 '22 03:09

Sam Corder