如何定义采用对象类型参数的对象方法



在这种情况下,将对象方法的参数的类型提示作为对象本身是明智的。

class ImagePath:
def __init__(self, path:Path, size:int):
self.path = path
self.size = size
def __eq__(self, other:ImagePath):
return self.path == other.path and self.size == other.size

但是,这会给出一个错误:

NameError: name 'ImagePath' is not defined

是否有一种方法可以用正确的类型提示构造方法?

p。我知道,如果没有equals方法,该方法将以相同的方式响应,但这是一个简单的示例。

将ImagePath放在引号中,像这样:

class ImagePath:
def __init__(self, path:Path, size:int):
self.path = path
self.size = size
def __eq__(self, other:'ImagePath'):
return self.path == other.path and self.size == other.size

参见PEP 484部分Forward Reference

从Python 3.7开始,使用PEP 563,您可以使用from __future__ import annotations将注释存储为字符串。源自PEP 563:

该PEP建议更改函数注释和变量注释,使它们不再在函数中求值定义时间。相反,它们保存在__annotations__中字符串形式。

此更改正在逐步引入,从__future__开始

from __future__ import annotations
class ImagePath:
def __init__(self, path:tuple, size:int):
self.path = path
self.size = size
def __eq__(self, other:ImagePath):
return self.path == other.path and self.size == other.size

ImagePath((10,22),20) == ImagePath((10,22),20)
# True
ImagePath((10,22),20) == ImagePath((10,), 20)
# False