问题

在Python3中,例如:构建链表节点类,会有一个指向自身类型的指针,代码如下:

1
2
3
4
5
class ListNode(object):
    value: int
    nextNode: ListNode
    def merge(self, head: ListNode):
        pass

如果直接写成这样,代码提示器是无法识别到的

解决

Python 3.10以及以后的版本

已经支持该方式

Python 3.7+ 使用feature

1
from __future__ import annotations

Python 3.6以及更旧的版本

直接使用字符串的方式,例如:

1
2
3
4
5
class ListNode(object):
    value: int
    nextNode: 'ListNode'
    def merge(self, head: 'ListNode'):
        pass

参考资料

https://stackoverflow.com/questions/33533148/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class