Linux/Unix > Python Essential Reference, Second Edition > 7. Classes and Object-Oriented Programming > Classes, Types, and Membership Tests | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105087128013202153097093

### Classes, Types, and Membership Tests

Currently, there’s a separation between types and classes. In particular, built-in types such as lists and dictionaries cannot be specialized via inheritance, nor does a class define a new type. In fact, all class definitions have a type of `ClassType`, while all class instances have a type of `InstanceType`. Thus, the following expression is true for any two objects that are instances of a class (even if they were created by different classes):

    type(a) == type(b)

To test for membership in a class, use the built-in function `isinstance(``obj` `,``cname` `)`. This function returns true if an object `obj` belongs to the class `cname` or any class derived from `cname` . For example:

    class A: pass
    class B(A): pass
    class C: pass

    a = A()          # Instance of 'A'
    b = B()          # Instance of 'B'
    c = C()          # Instance of 'C'

    isinstance(a,A)  # Returns 1
    isinstance(b,A)  # Returns 1, B derives from A
    isinstance(b,C)  # Returns 0, C not derived from A

Similarly, the built-in function `issubclass(``A` `,``B` `)` returns true if the class `A` is a subclass of class `B` . For example:

    issubclass(B,A)   # Returns 1
    issubclass(C,A)   # Returns 0

The `isinstance()` function can be used to perform type-checking against any of the built-in types:

    import types
    isinstance(3, types.IntType)     # Returns 1
    isinstance(3, types.FloatType)   # Returns 0

This is the recommended way to perform type-checking with the built-in types, as the distinction between types and classes may disappear in a future release.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.