Python3使用当前类进行返回注解NameError

2022-08-08,,,

背景
在python>=3.5的版本中加入了对函数声明的注解,可以用冒号:和箭头->对函数的入参和出参的类型进行注解,提高代码的可阅读性。

问题
在声明MyClass类的时候,其中一个入参_next的类型是该类本身的类型MyClass,如果直接按照下文中的写法,在调用时会报错。

class MyClass(object):
    def __init__(self, number: int, content: str,
    		_next: List[MyClass]) -> None:
    	self.number  = number
    	self.content = content
    	self._next   = _next

调用时报错NameError: name 'Section' is not defined

解决方案
_next: List[MyClass]中的MyClass修改为'MyClass'即整体代码改为

class MyClass(object):
    def __init__(self, number: int, content: str,
    		_next: List['MyClass']) -> None:
    	self.number  = number
    	self.content = content
    	self._next   = _next

调用时可正常运行,不再报错

本文地址:https://blog.csdn.net/weixin_48629601/article/details/107186657

《Python3使用当前类进行返回注解NameError.doc》

下载本文的Word格式文档,以方便收藏与打印。