简体   繁体   English

相当于Ruby'is_a?'的Python

[英]Python Equivalent to Ruby 'is_a?'

I'm wondering is there a Python Equivalent to Ruby's 'is_a?' 我想知道是否有一个与Ruby的“ is_a”等效的Python? method? 方法?

> "".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. 如果class是obj的类,或者class是obj的超类之一或obj中包含的模块,则返回true。

Thank you. 谢谢。

It depends on exactly what part you want. 这完全取决于您想要的部分。

If you want to know whether foo is an instance of class C or any of its ancestors, then: 如果您想知道fooC类的实例还是其任何祖先,则:

isinstance(foo, C)

If you want to know whether foo is an instance of C and only C , then: 如果您想知道foo是否是C的实例且仅是C的实例,则:

type(foo) == C

Broadly speaking, frequent use of things like isinstance(...) or type(...) is a code smell because it means duck typing is broken, and Python relies heavily on that sort of contract. 广义上讲,频繁使用isinstance(...)type(...)的代码是一种代码异味,因为这意味着鸭子类型被破坏了,而Python在很大程度上依赖于这种契约。 See, eg, isinstance considered harmful . 参见,例如, 被认为有害的实例

I've never used Ruby, but that functionality looks a lot like what isinstance does: 我从未使用过Ruby,但是该功能与isinstance功能非常相似:

>>> a = "string"
>>> isinstance(a, str)
True
>>>

Also, in case you don't know, here is a reference on str . 另外,如果您不知道,这是str的参考。

有一个isinstance(a,b)函数来检查a是否为b类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM