Is there a static constructor or static initializer in Python?

2024/11/21 0:18:28

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()@propertydef 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.

Answer

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.

https://en.xdnf.cn/q/26261.html

Related Q&A

What does this - in jinja2 template engine do?

I am learning jinja2 because Google App Engine recommends it.I found this example on Wikipedia: http://en.wikipedia.org/wiki/Jinja_%28template_engine%29{%- for item in item_list %}{{ item }}{% if not l…

When to apply(pd.to_numeric) and when to astype(np.float64) in python?

I have a pandas DataFrame object named xiv which has a column of int64 Volume measurements. In[]: xiv[Volume].head(5) Out[]: 0 252000 1 484000 2 62000 3 168000 4 232000 Name: Volume, d…

How to change folder names in python?

I have multiple folders each with the name of a person, with the first name(s) first and the surname last. I want to change the folder names so that the surname is first followed by a comma and then t…

Python return list from function

I have a function that parses a file into a list. Im trying to return that list so I can use it in other functions. def splitNet():network = []for line in open("/home/tom/Dropbox/CN/Python/CW2/net…

Python Json loads() returning string instead of dictionary?

Im trying to do some simple JSON parsing using Python 3s built in JSON module, and from reading a bunch of other questions on SO and googling, it seems this is supposed to be pretty straightforward. Ho…

Sort dataframe by string length

I want to sort by name length. There doesnt appear to be a key parameter for sort_values so Im not sure how to accomplish this. Here is a test df:import pandas as pd df = pd.DataFrame({name: [Steve, Al…

How to mock pythons datetime.now() in a class method for unit testing?

Im trying to write tests for a class that has methods like:import datetime import pytzclass MyClass:def get_now(self, timezone):return datetime.datetime.now(timezone)def do_many_things(self, tz_string=…

How can I select only one column using SQLAlchemy?

I want to select (and return) one field only from my database with a "where clause". The code is:from sqlalchemy.orm import load_only@application.route("/user", methods=[GET, POST])…

Get first list index containing sub-string?

For lists, the method list.index(x) returns the index in the list of the first item whose value is x. But if I want to look inside the list items, and not just at the whole items, how do I make the mos…

TypeError: Invalid dimensions for image data when plotting array with imshow()

For the following code# Numerical operation SN_map_final = (new_SN_map - mean_SN) / sigma_SN # Plot figure fig12 = plt.figure(12) fig_SN_final = plt.imshow(SN_map_final, interpolation=nearest) plt.col…