Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Singleton is what you need. Here is a simple example. Note that everything still works as expected if you're importing and using the singleton in other modules (and that's the whole point).</p> <pre><code>def singleton(cls): return cls() @singleton class EventManager: def __init__(self): self.events = [] def add_event(self, event): self.events.append(event) def print_events(self): print("Events : {}".format(self.events)) EventManager.add_event(0) EventManager.add_event(1) EventManager.add_event(2) EventManager.print_events() </code></pre> <p>Output:</p> <pre><code>Events : [0, 1, 2] </code></pre> <p>EDIT</p> <p>You asked : <code>The thing is that I initialize the class with a variable like EventManager(var), what shall I do in this case?</code> </p> <p>What you need to understand is that EventManager will be instantiated right after the class definition, which means the first time the module containing <code>EventManager</code> is imported. Since <code>EventManager</code> is a singleton, I don't think there is a point initializing the singleton with a variable. Even though it is possible:</p> <pre><code>def singleton_with_args(*args, **kwargs): def wrapper(cls): return cls(*args, **kwargs) return wrapper @singleton_with_args(0) class EventManager: def __init__(self, first_event): self.events = [first_event] def add_event(self, event): self.events.append(event) def print_events(self): print("Events : {}".format(self.events)) EventManager.add_event(1) EventManager.add_event(2) EventManager.add_event(3) EventManager.print_events() </code></pre> <p>Output:</p> <pre><code>Events : [0, 1, 2, 3] </code></pre> <p>It works but as I said, I don't think it's useful. You could as well use methods or module variables to initialize your singleton.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload