Manage class instancing on a global scope in python
I wish to control the time of instancing of a class MyClass, it needs to be unique and be able to reference it globally
# myclass.py
class MyClass():
def __init__(self):
pass
def hello(self):
return 'world'
class MyManager():
def __init__(self):
self.instance = None
def create(self):
self.instance = MyClass
manager = MyManager
The reason for this is because the class im working with have some dependencies at initialization which do not exist at the time of modu开发者_开发知识库le import. (For the sake of the example above, I've left out the dependency)
# main.py
import myclass
myclass.manager.create
instance = myclass.manager.instance
hello = instance.hello
Now this is giving an error:
AttributeError: class MyManager has no attribute 'instance'
Im relatively new to python, and have mostly been using it for linear scripts. What am i missing?
You never actually call myclass.manager.create()
, since you forgot the parens. Add them. You probably meant to call MyManager()
and MyClass()
as well, in order to instantiate them.
精彩评论