【问题标题】:Why is the isinstance() function not working?为什么 isinstance() 函数不起作用?
【发布时间】:2021-07-25 15:25:14
【问题描述】:

例如:

def test(arg = False):
    return arg, type(arg), isinstance(arg, int)

print(test())

将导致:

False, <class: 'bool', True>

arg 变量是False,显然是boolean。 type() 函数做对了,但为什么 isinstance() 函数说 arg 是 int?这是一个错误吗?

注意:我使用的是 Python 3.8.5

【问题讨论】:

  • 因为issubclass(bool, int)

标签: python python-3.x types boolean isinstance


【解决方案1】:

因为bool对象是int对象,换句话说:

>>> issubclass(bool, int)
True

或者,换一种说法:

>>> bool.mro()
[<class 'bool'>, <class 'int'>, <class 'object'>]

【讨论】:

  • 那我该怎么办?
  • @TonyStark,如果您正在测试特定类型,即不考虑继承,请使用 type() 而不是 isinstance()
  • @Michael Ruth 谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-06-17
  • 2014-08-06
  • 2015-02-20
  • 2021-08-20
  • 2013-08-26
  • 2011-11-13
  • 2023-03-15
  • 2021-08-26
相关资源
最近更新 更多