【问题标题】:typed python: using the classes' own type inside class definition [duplicate]类型化的python:在类定义中使用类自己的类型[重复]
【发布时间】:2017-08-08 07:54:25
【问题描述】:

以下代码无法按预期工作。显然,我不能在类定义中使用类自己的类型:

class Foo:
    def __init__(self, key :str) -> None:
        self.key = key

    def __eq__(self, other :Foo) -> bool:
        return self.key == other.key

print('should be true: ', Foo('abc') == Foo('abc'))
print('should be false: ', Foo('abc') == Foo('def'))

运行结果是:

Traceback (most recent call last):
  File "class_own_type.py", line 1, in <module>
    class Foo:
  File "class_own_type.py", line 5, in Foo
    def __eq__(self, other :Foo) -> bool:
NameError: name 'Foo' is not defined

另外,使用mypy 检查代码返回:

class_own_type.py:5: error: Argument 1 of "__eq__" incompatible with supertype "object"

如何更正此代码以使其对 Python 和 mypy 均有效?

【问题讨论】:

    标签: python type-hinting mypy


    【解决方案1】:

    名称Foo 尚未绑定,因为在您尝试使用该名称时尚未定义类本身(请记住:函数参数是在函数定义时评估的,而不是在函数调用时)。

    从 Python 3.7+ 开始,您可以通过在模块顶部添加此导​​入来 postpone evaluation of annotations

    from __future__ import annotations
    

    在 Python 3.10 中,延迟评估将成为默认行为。对于 Python

    class Foo:
        def __init__(self, key :str) -> None:
            self.key = key
    
        def __eq__(self, other: 'Foo') -> bool:
            return self.key == other.key
    
    print('should be true: ', Foo('abc') == Foo('abc'))
    print('should be false: ', Foo('abc') == Foo('def'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 2018-03-12
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多