Python @ DjangoSpin

Python: Using builtin functions isinstance() & issubclass()

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Using isinstance() & issubclass() in Python

Using isinstance() & issubclass() in Python

isinstance()

The builtin function isinstance(obj, cls) returns True if obj is an instance of class cls, else returns False.

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

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.).

	
### EXAMPLES ###
>>> if isinstance(4, int):
	print("4 is an integer!")
	
4 is an integer!


>>> isinstance(4, str)
False
>>> isinstance(4, int)
True


>>> class Man(object): pass
>>> ethan = Man()
>>> isinstance(ethan, Man)
True	

If you are uncertain about the exact parent class of the object, you can insert all the likely classes in the form of a tuple. The isinstance() function will return True if the object belongs to either of the specified classes.

>>> isinstance(4, (str, int) )
True

Keep in mind that all builtin-classes, data types, user-defined classes inherit from the class called object.


issubclass()

The builtin function issubclass(subClass, superClass) returns True if the class subClass is a subclass of the class superClass, else it returns False.

>>> help(issubclass)
Help on built-in function issubclass in module builtins:

issubclass(...)
    issubclass(C, B) -> bool
    
    Return whether class C is a subclass (i.e., a derived class) of class B.
    When using a tuple as the second argument issubclass(X, (A, B, ...)),
    is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).
	
### EXAMPLE ###
>>> class Person(object): pass
>>> class Man(Person): pass
>>> class Woman(Person): pass

>>> issubclass(Man, Person)
True

>>> issubclass(Man, object)
True

>>> issubclass(Woman, Man)
False

If you are uncertain about the exact parent class of a subclass, you can insert all the likely classes in the form of a tuple. The issubclass() function will return True if the class specified is a subclass of either of the specified classes.

>>> issubclass( Man, (Person, Woman) )
True
>>> issubclass( Person, (Man, Woman) )
False

Keep in mind that all builtin-classes, data types, user-defined classes inherit from the class called object.


See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply