typed python: using the classes' own type inside class definition [duplicate]

雨燕双飞 提交于 2019-11-28 11:32:32

问题


The following code does not work as expected. Apparently, I cannot use the classes' own type inside class definition:

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

The result of running it is:

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

Also, checking the code with mypy returns:

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

How can I correct this code to be valid, both for Python and for mypy?


回答1:


The name Foo isn't bound yet, because the class itself has not yet been defined at the time that you try to use the name (remember: function arguments are evaluated at function definition time, not at function call time).

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


来源:https://stackoverflow.com/questions/42845972/typed-python-using-the-classes-own-type-inside-class-definition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!