Steven Bayer
Steven Bayer

Reputation: 2127

Using instance of class

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

Answers (2)

darksky
darksky

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

pythad
pythad

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

Related Questions