如何在整个项目中共享 class 的实例?

How to share an instance of a class across an entire project?

我正在开发一个 python 库,它通过 class 连接其功能。库的用户需要在首次将其导入到他们的项目中时对其进行实例化。在此之后,库对象将具有一些我希望在用户的整个项目中共享的状态。

像这样:

图书馆

class Lib():

  def __init__(self, msg):
    self.msg = msg

  def print_msg():
    print(self.msg)

submod1

from lib import Lib

def test():
  # something like this
  Lib.print_msg()

submod2

from lib import Lib

def test():
  # something like this
  Lib.print_msg()

用户的主要

from lib import Lib:
import submod1, submod2

lib = Lib('message')

submod1.test()
submod2.test()

输出

message
message

看起来 Singleton class 很适合您的用例。在 python 中实现单例 class 有多种方法。请参阅 this 答案以获得更详细的解释。

尽管对于您的用例,您可以这样做:

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            # don't want __init__ to be called every time
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class Lib(metaclass=Singleton):
    def __init__(self, msg):
        self.msg = msg

    def print_msg():
        print(self.msg)

submod1

from lib import Lib

    def test():
        Lib().print_msg()

主文件

from lib import Lib:
import submod1, submod2

    lib = Lib('message')

    submod1.test()
    submod2.test()

Lib.py:

class Lib:
    msg = ""
    __init__ = None

    @classmethod
    def print_msg(cls):
        print(cls.msg)

也许是这样的?

首次使用:

Lib.msg = "abc"
Lib.print_msg()

第二次使用:

Lib.print_msg()