Interview Questions

How do I check if an object is an instance of a given class or of a subclass of it?

Python Questions and Answers


(Continued from previous question...)

How do I check if an object is an instance of a given class or of a subclass of it?

Use the built-in function isinstance(obj, cls). You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. isinstance(obj, (class1, class2, ...)), and can also check whether an object is one of Python's built-in types, e.g. isinstance(obj, str) or isinstance(obj, (int, long, float, complex)).

Note that most programs do not use isinstance() on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object's class and doing a different thing based on what class it is. For example, if you have a function that does something:

def search (obj):
if isinstance(obj, Mailbox):
# ... code to search a mailbox
elif isinstance(obj, Document):
# ... code to search a document
elif ...

A better approach is to define a search() method on all the classes and just call it:

class Mailbox:
def search(self):
# ... code to search a mailbox

class Document:
def search(self):
# ... code to search a document

obj.search()

(Continued on next question...)

Other Interview Questions