繁体   English   中英

在python中在全局范围内管理类实例化

[英]Manage class instancing on a global scope in python

我希望控制实例MyClass的实例化时间,它必须是唯一的并且能够在全局范围内引用它

# 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

原因是因为正在使用的类在初始化时具有某些依赖项,而这些依赖项在模块导入时不存在。 (为了上面的示例,我省略了依赖项)

# main.py
import myclass

myclass.manager.create

instance = myclass.manager.instance

hello = instance.hello

现在这给出了一个错误:

AttributeError: class MyManager has no attribute 'instance'

我对python来说相对较新,并且主要用于线性脚本。 我想念什么?

您实际上从未调用过myclass.manager.create() ,因为您忘记了括号。 添加它们。 您可能MyManager()调用MyManager()MyClass()以便实例化它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM