Can you write code to check whether the given object belongs to a class or its subclass?

Python has a built-in method to list the instances of an object that may consist of many classes. It returns in the form of a table containing tuples instead of the individual classes. Its syntax is as follows.

<isinstance(obj, (class1, class2, ...))>

The above method checks the presence of an object in one of the classes. The built-in types can also have many formats of the same function like <isinstance(obj, str)> or <isinstance(obj, (int, long, float, complex))>.

Also, it’s not recommended to use the built-in classes. Create an user-defined class instead.

We can take the following example to determine the object of a particular class.

Example.

def lookUp(obj):
    if isinstance(obj, Mailbox):
        print "Look for a mailbox"
    elif isinstance(obj, Document):
        print "Look for a document"
    else:
        print "Unidentified object"
Posted on by