class Node:
def append_child(self, node: Node):
if node != None:
self.first_child = node
self.child_nodes += [node]
我该怎么做node: Node
?因为当我运行它时,它说name 'Node' is not defined
.
我应该删除: Node
并在函数内部实例检查它?
但是我怎样才能访问node
的属性(我希望它是Node
class)?
顺便说一句,我不知道如何在 Python 中实现类型转换。
类型检查中的“self”引用通常使用字符串完成:
class Node:
def append_child(self, node: 'Node'):
if node != None:
self.first_child = node
self.child_nodes += [node]
这在“转发参考文献”PEP-0484 的部分。
Please note that this doesn't do any type-checking or casting. This is a type hint which python (normally) disregards completely1. However, third party tools (e.g. mypy), use type hints to do static analysis on your code and can generate errors before runtime.
另外,从 python3.7 开始,您可以隐含地使用以下命令将所有类型提示转换为模块内的字符串from __future__ import annotations
(在 python4.0 中,这将是默认值)。
1The hints are introspectable -- So you could use them to build some kind of runtime checker using decorators or the like if you really wanted to, but python doesn't do this by default.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)