gpt4 book ai didi

python - 为什么 isinstance() 方法返回 True(Python 3.xx)

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:30 25 4
gpt4 key购买 nike

我还不太熟悉 Python 的 OOP 方面,所以这有点超出我的理解范围。

>>> a=[[2,3,4]]
>>> types = (list,str,int,str,int)
>>> b=isinstance(a,types)

True

无论我在列表类型后添加什么类型,表达式总是返回 True

我读过 isinstance() 方法接受派生类类型,但我无法真正说服自己我知道这里发生了什么。

这也返回 true。是因为 3 个都属于同一个类吗?

>>> isinstance([], (tuple, list, set))
True

最佳答案

In [1]: isinstance?

Docstring:

isinstance(object, class-or-type-or-tuple) -> bool

Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object's type. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for:

isinstance(x, A) or isinstance(x, B) or ... (etc.).

Type: builtin_function_or_method

所以,它实际上是一个语句。很清楚,对吧?

关于python - 为什么 isinstance() 方法返回 True(Python 3.xx),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32001909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com