Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

Is there a static constructor or static initializer in 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.

question from:https://stackoverflow.com/questions/7396092/is-there-a-static-constructor-or-static-initializer-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hint: anything that references self is going to require an instantiation of the class. You could do it like this:

class App:
    email_queue = EmailQueue()

App.email_queue.DoSomething()

But come on, that seems like a lot of fluff. I'm with SLaks, just initialize it outside of the class. Alternatively, you could look into the singleton pattern.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...