Python 参数的类型检查 [英] Type checking of arguments Python

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

问题描述

有时需要检查 Python 中的参数.例如我有一个函数,它接受网络中其他节点的地址作为原始字符串地址或封装其他节点信息的类 Node.

Sometimes checking of arguments in Python is necessary. e.g. I have a function which accepts either the address of other node in the network as the raw string address or class Node which encapsulates the other node's information.

我使用 type() 函数:

I use type() function as in:

    if type(n) == type(Node):
        do this
    elif type(n) == type(str)
        do this

这是一个很好的方法吗?

Is this a good way to do this?

更新 1: Python 3 对函数参数进行了注释.这些可用于使用工具进行类型检查:http://mypy-lang.org/

Update 1: Python 3 has annotation for function parameters. These can be used for type checks using tool: http://mypy-lang.org/

推荐答案

使用 isinstance().示例:

if isinstance(n, unicode):
    # do this
elif isinstance(n, Node):
    # do that
...

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

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