类中的类型提示 [英] type hinting within a class

查看:50
本文介绍了类中的类型提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

How do I do node: Node? Because when I run it, it says name 'Node' is not defined.

我是否应该删除 : Node 并在函数内部对其进行实例检查?但是,我如何访问 node 的属性(我希望它是 Node 类的实例)?

Should I just remove the : Node and instance check it inside the function? But then how could I access node's properties (which I would expect to be instance of Node class)?

顺便说一句,我不知道如何在 Python 中实现类型转换.

I don't know how implement type casting in Python, BTW.

推荐答案

self"类型检查中的引用通常使用字符串完成:

"self" references in type checking are typically done using strings:

class Node:
    def append_child(self, node: 'Node'):
       if node != None:
        self.first_child = node
    self.child_nodes += [node]

这在 前向引用" PEP-0484 部分.

This is described in the "Forward references" section of PEP-0484.

请注意,这不会进行任何类型检查或强制转换.这是一个类型提示,python(通常)完全忽略1.但是,第三方工具(例如 mypy)使用类型提示对您的代码进行静态分析,并可能在运行前生成错误.

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,这将是默认值).

Also, starting with python3.7, you can implicitly convert all of your type-hints to strings within a module by using the from __future__ import annotations (and in python4.0, this will be the default).

1提示内省的——所以如果你真的想的话,你可以使用它们来构建某种使用装饰器等的运行时检查器,但是python默认不会这样做.

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.

这篇关于类中的类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆