【问题标题】:Importing Global instance of a Class in Python在 Python 中导入类的全局实例
【发布时间】:2021-01-30 11:25:06
【问题描述】:

在 Python 中,我尝试创建一些全局对象,如果已导入模块(类似于日志记录模块),这些对象在程序中的任何位置都可用。

例如:

模块:databaseinterface.py

导入 sqlite3

数据库 = 无

类数据库:

def init(自我,位置):...

def ViewQuery(self, query, params): ...

def ModifyQuery(self, query, params): ...

定义创建数据库(位置):

如果不是数据库:

DATABASE = 数据库(位置)

模块:main.py

导入数据库接口

databaseinterface.create_database("test.sqlite") results = databaseinterface.DATABASE.ViewQuery("SELECT * from users")

但我收到错误“ViewQuery”不存在。有没有一种巧妙的方法可以从导入中获得全局实例?

干杯, 布拉德

【问题讨论】:

    标签: python class import


    【解决方案1】:

    你想要的是一个单例类结构。是一种常见的代码设计模式。

    有很多资源。例如This Blog post 或者直接使用:https://duckduckgo.com/?q=python+singleton

    示例代码片段:

    class SingletonGovt:
       __instance__ = None
    
       def __init__(self):
           """ Constructor.
           """
           if SingletonGovt.__instance__ is None:
               SingletonGovt.__instance__ = self
           else:
               raise Exception("You cannot create another SingletonGovt class")
    
       @staticmethod
       def get_instance():
           """ Static method to fetch the current instance.
           """
           if not SingletonGovt.__instance__:
               SingletonGovt()
           return SingletonGovt.__instance__
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-12
      • 2017-03-26
      • 2022-06-23
      • 1970-01-01
      相关资源
      最近更新 更多