抽象基类或类型.支持__str__的协议



是否有一个内置的ABC来强制__str__在子类中实现?或者输入协议?

我想要一个只接受__str____hash____eq__类的函数。我找到了Hashable,但没有找到Stringable

没有这样的内置ABC。实际上,每个类都有这个从object继承来的方法:

内置类型object定义的默认实现调用object.repr() .

见文档。


In [1]: class Foo: pass
In [2]: str(Foo())
Out[2]: '<__main__.Foo object at 0x7fcf10e219f0>'
In [3]: print(Foo())
<__main__.Foo object at 0x7fcf10e23d00>
In [4]: print(Foo().__str__())
<__main__.Foo object at 0x7fcf10e20d60>
In [5]: print(Foo().__repr__())
<__main__.Foo object at 0x7fcf10e20af0>
In [6]: object().__repr__()
Out[6]: '<object object at 0x7fcf119c6810>'
In [7]: object().__str__()
Out[7]: '<object object at 0x7fcf119c67c0>'

没有这样的内置抽象类,但是您可以强制执行这些需求。

from abc import ABC, abstractmethod

class Required(ABC):
@abstractmethod
def __str__(self) -> str:
...
@abstractmethod
def __hash__(self) -> int:
...
@abstractmethod
def __eq__(self, other) -> bool:
...
>>> class Impl(Required): ...
>>> i = Impl()
TypeError: Can't instantiate abstract class Impl with abstract methods __eq__, __hash__, __str__

另外,您可以在运行时检查特定的结构子类型是否相等,如果不是这样,则返回TypeError(但这可能不是最佳实践):

from typing import Protocol, runtime_checkable

@runtime_checkable
class HasValue(Protocol):
value: int

class Impl(Required):
# also define __str__ and __hash__
@property
def value(self):
return 42
def __eq__(self, other):
if not isinstance(other, HasValue):
raise TypeError
return self.value == other.value

class Valued:
value = 42

class NotValued:
...
>>> i = Impl()
>>> v = Valued()
>>> n = NotValued()
>>> i == v  # both have self.value
True
>>> v == n  # self.value not enforced
False
>>> i == n  # self.value enforced
TypeError

相关内容

  • 没有找到相关文章

最新更新