Reputation: 2127
Is there a "pythonic" way to use an instance of a class for a module. For example:
class MyClass:
def __init__(self):
self.my_var = "cool value"
_instance = MyClass()
def getInstance():
return _instance()
The goal is to share large lookup classes through the application instead of initializing them on every import.
Upvotes: 2
Views: 482
Reputation: 2080
If your instances are dynamically created somehow, and you really need to keep track of them, you can override __new__
, like this:
class MyClass:
instances = []
def __new__(cls, *args, **kwargs):
my_instance = super(MyClass, cls).__new__(cls, *args, **kwargs)
MyClass.instances.append(my_instance)
return my_instance
a = MyClass()
print(MyClass.instances)
Upvotes: 0
Reputation: 4267
You can import anything from a module. Class instance is not an exception:
file1.py
class MyClass:
def __init__(self):
self.my_var = "cool value"
instance = MyClass()
file2.py
from file1 import instance
Upvotes: 3