true Info: is_a?(class) → true or false Re-6ren">
gpt4 book ai didi

Python 相当于 Ruby 'is_a?'

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:37 25 4
gpt4 key购买 nike

我想知道是否存在与 Ruby 的“is_a”等效的 Python?方法?

> "".is_a? String
=> true

Info:

is_a?(class) → true or false

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

谢谢。

最佳答案

这取决于你想要什么部分。

如果您想知道 foo 是否是类 C 或其任何祖先的实例,则:

isinstance(foo, C)

如果你想知道foo是否是C的一个实例并且只是C,那么:

type(foo) == C

从广义上讲,频繁使用诸如 isinstance(...)type(...) 之类的东西是一种代码味道,因为这意味着鸭子类型被破坏了, Python 在很大程度上依赖于这种契约。参见,例如, isinstance considered harmful .

关于Python 相当于 Ruby 'is_a?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20406631/

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