抽象基类或打字。支持__STR______________

发布于 2025-01-24 12:08:54 字数 207 浏览 0 评论 0原文

是否有用于在子类中实现的__ str __的内置ABC?还是打字协议?

我想要一个仅接受__ str __ __ HASH ____ eq __的功能。我找到了Hashable,但不是Stringable

Is there a builtin ABC for enforcing __str__ to be implemented in subclasses? Or a typing protocol?

I want a function that only accepts classes with __str__ __hash__ and __eq__. I've found Hashable but not Stringable

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月打碎记忆 2025-01-31 12:08:54

没有此类内置ABC。实际上,每个班级都有此方法从object

内置类型对象呼叫对象定义的默认实现。 repr ()。

请参阅 docs


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>'

There is no such built-in ABC. In fact, every class has this method inherited from object:

The default implementation defined by the built-in type object calls object.repr().

See docs.


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>'
旧街凉风 2025-01-31 12:08:54

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

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

There's no such a builtin abstract class, but you can enforce those requirements.

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__

Also, you could check a specific structural subtyping for equality at runtime, and return a TypeError if it's not the case (but it may not be a best practice):

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文