类型注释旨在帮助人们阅读代码、静态分析工具和文档工具。即使可以执行您拥有的代码(我的意思是没有NameError),它实际上也不会强制执行任何操作。
在 python 中,实际执行一个特定的类通常被认为是不好的风格,你通常期望一个特定的接口(比如具有一个特定的属性):
class Vector(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
try:
return Vector(self.x + other.x, self.y + other.y)
except AttributeError: # the other had no x or y attribute
raise TypeError('cannot add Vector to {}'.format(type(other)))
或者只是省略 try 和 except 并让它与 AttributeError 一起失败:
class Vector(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
它没有提供信息的异常消息(你需要一个吗?)但是当other 没有x 或y 属性时它仍然会失败。
如果我误解了您的问题,而它只是关于“如何添加类型提示”,那么您只需将其包装为字符串(称为“前向引用”):
class Vector(object):
def __add__(self, other: 'Vector'):
...
他们甚至在 PEP 484 中有一个类似的例子:
当类型提示包含尚未定义的名称时,该定义可以表示为字符串文字,稍后再解析。
这种情况经常发生的情况是定义容器类,其中被定义的类出现在某些方法的签名中。例如,下面的代码(一个简单的二叉树实现的开始)不起作用:
class Tree:
def __init__(self, left: Tree, right: Tree):
self.left = left
self.right = right
为了解决这个问题,我们写:
class Tree:
def __init__(self, left: 'Tree', right: 'Tree'):
self.left = left
self.right = right