15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

13.12. Built-in Functions for Classes, Instances, and Other Objects<br />

13.12.1. issubclass()<br />

The issubclass() Boolean function determines if one class is a subclass or descendant of another class.<br />

It has the following syntax:<br />

issubclass(sub, sup)<br />

issubclass() returns TRue if the given subclass sub is indeed a subclass of the superclass sup (and False<br />

otherwise). This function allows for an "improper" subclass, meaning that a class is viewed as a subclass<br />

of itself, so the function returns true if sub is either the same class as sup or derived from sup. (A<br />

"proper" subclass is strictly a derived subclass of a class.)<br />

Beginning with <strong>Python</strong> 2.3, the second argument of issubclass() can be tuple of possible parent classes<br />

for which it will return true if the first argument is a subclass of any of the candidate classes in the given<br />

tuple.<br />

13.12.2. isinstance()<br />

The isinstance() Boolean function is useful for determining if an object is an instance of a given class. It<br />

has the following syntax:<br />

isinstance(obj1, obj2)<br />

isinstance() returns TRue if obj1 is an instance of class obj2 or is an instance of a subclass of obj2 (and<br />

False otherwise), as indicated in the following examples:<br />

>>> class C1(object): pass<br />

...<br />

>>> class C2(object): pass<br />

...<br />

>>> c1 = C1()<br />

>>> c2 = C2()<br />

>>> isinstance(c1, C1)<br />

True<br />

>>> isinstance(c2, C1)<br />

False<br />

>>> isinstance(c1, C2)<br />

False

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!