在类定义中使用类自己的类型[重复]

问题描述 投票:0回答:1

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

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个回答
65
投票

当定义

Foo.__eq__
时,名称
Foo
仍然未绑定,因为类本身尚未创建。请记住:函数参数在函数定义时计算,而不是在函数调用时计算。

从 Python 3.7+ 开始,您可以通过在模块顶部添加此导入来推迟注释的评估:

from __future__ import annotations
对于Python 

< 3.7, you can use string literals to delay evaluation of the type:

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'))
    
© www.soinside.com 2019 - 2024. All rights reserved.