【发布时间】:2020-12-02 01:06:51
【问题描述】:
我想在 python 中将我的派生类变成一个单例。我想通过元类实现单例,但总是遇到以下错误:
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
我的代码:
# singleton.py
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
# base.py
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def run(self, value):
pass
# foo.py
from base import Base
from singleton import Singleton
class Foo(Base, metaclass=Singleton):
def run(self, value):
print(value)
# main.py
from foo import Foo
f1 = Foo()
print(f1)
f1.run(42)
f2 = Foo()
print(f2)
f2.run(24)
【问题讨论】:
标签: python