In Python 3, I want to write a class that should only be used as a mixin. Is there any way to prevent direct creation of it?
Here's a simple concrete example:
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())))
However, I want to allow
class Bar(EqMixin):
...
without allowing
foo = EqMixin()
How to do that?
Note: I can't just raise an exception in the __init__
of EqMixin, because the __init__
might be called by Bar's __init__
.
Note: I don't want an abstract base class (or at least, I don't want to put any abstract methods into my mixin).
Maybe this would do:
>>> 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
Usage:
>>> class Defuse(MustBeMixed):
... def __init__(self):
... super().__init__()
<__main__.Defuse object at 0x1099f8990>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With