Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare inheritance with several classes?

Tags:

python

I want to check if an object is an instance of any class in a list/group of Classes, but I can't find if there is even a pythonic way of doing so without doing

if isinstance(obj, Class1) or isinstance(obj, Class2) ... or isinstance(obj, ClassN):
    # proceed with some logic

I mean, comparing class by class.

It would be more likely to use some function similar to isinstance that would receive n number of Classes to compare against if that even exists.

Thanks in advance for your help!! :)

like image 875
Gerard Avatar asked May 05 '12 01:05

Gerard


People also ask

Can you inherit from multiple classes?

When one class extends more than one classes then this is called multiple inheritance. For example: Class C extends class A and B then this type of inheritance is known as multiple inheritance.

Which inheritance has multiple parent classes?

multiple inheritance allows a child class to inherit from more than one parent class.

How many classes are there in multiple inheritance?

Details. In object-oriented programming (OOP), inheritance describes a relationship between two classes in which one class (the child class) subclasses the parent class.

How do you handle multiple inheritance?

The only way to implement multiple inheritance is to implement multiple interfaces in a class. In java, one class can implements two or more interfaces. This also does not cause any ambiguity because all methods declared in interfaces are implemented in class.


1 Answers

You can pass a tuple of classes as 2nd argument to isinstance.

>>> isinstance(u'hello', (basestring, str, unicode))
True

Looking up the docstring would have also told you that though ;)

>>> 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.).
like image 70
Glider Avatar answered Oct 23 '22 15:10

Glider