【问题标题】:Check if a variable is instance of a type or None检查变量是类型的实例还是无
【发布时间】:2018-11-26 11:39:51
【问题描述】:

我有一个变量可以是intNone。如果是别的,我会报错。

我有以下代码:

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

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

【问题讨论】:

  • 当您需要时,德摩根的法律规范在哪里...
  • 给你:deMorgan

标签: python python-3.x python-3.5 python-3.6


【解决方案1】:

首先,你需要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')

解释:您正在检查变量是否 both 不是 int 并且 不是 None,因为正如您所说,检查其中一个 或另一个总是True

如果您希望将其缩小到单次检查,您可以这样做:

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

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

【讨论】:

  • not isinstance(id, (int, )) and id is not None也可以表示为not (id is None or isinstance(id, int)),这样更容易理解。
  • @brunodesthuilliers 确实如此,但由于目标是只移动到一个 not 条件,我找到了将两者包含在同一个 isinstance 中的方法,更具可读性
  • 我并不是说您的第二个解决方案在这种情况下不好,只是作为更通用的解决方案,您可以将not A and not B 转换为not (A or B)(一个否定),这被证明是更容易被普通人脑理解。
  • 同意,没错
猜你喜欢
  • 2015-04-29
  • 2011-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
  • 2014-03-19
相关资源
最近更新 更多