[英]Check whether class instance variable with same name as specified function is None or not
[英]Check if a variable is instance of a type or None
我有一个可以是int
或None
的变量。 如果是其他事情,我会引发错误。
我有以下代码:
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.