python - 参数类型检查 Python

标签 python typechecking

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

我使用 type() 函数如下:

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

这是一个好方法吗?

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

最佳答案

使用 isinstance()。示例:

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

关于python - 参数类型检查 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/734368/

相关文章:

python - 在 AWS Lambda 上使用 Tensorflow 部署微服务

python - 计算具有不同采样点数量的离散函数的平均值

python - 使用 Python 将现有 netcdf 文件中的 Nans 替换为 -9999

python - TypeError 使用 GradientTape.gradient 计算梯度

haskell - 如何声明在 let 中定义的函数的类型

java - 在 Java 中高效地编码管理变量类型的参数

swift - 类型(: ) in Swift 3 does not seem to work with the is type check

python - 使用terminaltables,如何将所有数据保存在单个表中,而不是拆分到多个表中?

flutter - 如何强制 Flutter/Dart 要求类型?

haskell - fix 只能用非严格评估语言输入吗?