繁体   English   中英

检查变量是类型的实例还是无

[英]Check if a variable is instance of a type or None

我有一个可以是intNone的变量。 如果是其他事情,我会引发错误。

我有以下代码:

if not isinstance(id, int) or id is not None:
    raise AttributeError('must be called with a id of type INT or NONE')

这是行不通的,因为每个条件都会否定另一个,并且总是会引发错误。

首先,你需要and而不是or

if not isinstance(id, (int, )) and id is not None:
    raise AttributeError('must be called with a id of type INT or NONE')

说明:您要检查,看是否该变量既是不是int ,而不是None ,因为如你所说,检查一个另一个始终是True

如果您希望将其范围缩小到单个检查,您可以执行以下操作:

if not isinstance(id, (int, type(None))):
    raise AttributeError('must be called with a id of type INT or NONE')

注意:您正在使用该名称隐藏内置id函数,请尝试使用不同的函数以避免其他奇怪的错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM