当前位置: 移动技术网 > IT编程>脚本编程>Python > Python3使用当前类进行返回注解NameError

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

2020年07月08日  | 移动技术网IT编程  | 我要评论

背景
在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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网