在Python3中,如何防止直接创建mixin类?

2024-06-16 11:49:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python3中,我想编写一个只能用作mixin的类。有没有办法阻止它的直接产生?你知道吗

下面是一个简单的具体例子:

class EqMixin:
    def __eq__(self, other):
        return type(self) == type(other) and self.__dict__ == other.__dict__
    def __hash__(self):
        return hash(tuple(sorted(self.__dict__.items())))

但是,我想允许

class Bar(EqMixin):
    ...

不允许

foo = EqMixin()

怎么做?你知道吗

注意:我不能在EqMixin的__init__中引发异常,因为__init__可能由Bar的__init__调用。你知道吗

注意:我不想要抽象基类(或者至少,我不想在mixin中放入任何抽象方法)。你知道吗


Tags: selfreturninitdeftypebarhashmixin
2条回答

也许这样可以:

>>> class MustBeMixed(object):
...     def __init__(self):
...         if self.__class__ == MustBeMixed:
...             raise TypeError

>>> MustBeMixed()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
TypeError

用法:

>>> class Defuse(MustBeMixed):
...     def __init__(self):
...         super().__init__()
<__main__.Defuse object at 0x1099f8990>

听起来你想创建一个abstract base class。也许使用^{}模块?只要类上至少有一个抽象方法没有被重写,就不能实例化该类。你知道吗

相关问题 更多 >