有时检查 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/