如何比较继承与几个类?

Ger*_*ard 9 python

我想检查一个对象是否是Classes列表/组中任何类的实例,但我无法找到是否有一个pythonic方式这样做而不做

if isinstance(obj, Class1) or isinstance(obj, Class2) ... or isinstance(obj, ClassN):
    # proceed with some logic
Run Code Online (Sandbox Code Playgroud)

我的意思是,逐个比较.

更有可能使用类似于isinstance接收n个Classes的函数来进行比较,如果它甚至存在的话.

在此先感谢您的帮助!!:)

Gli*_*der 28

您可以将类的元组作为第二个参数传递给isinstance.

>>> isinstance(u'hello', (basestring, str, unicode))
True
Run Code Online (Sandbox Code Playgroud)

查找docstring也会告诉你虽然;)

>>> help(isinstance)
Help on built-in function isinstance in module __builtin__:

isinstance(...)
    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.).
Run Code Online (Sandbox Code Playgroud)