Linux/Unix > Python Essential Reference, Second Edition > 3. Types and Objects > Object Identity and Type | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104028131049071235155082

### Object Identity and Type

The built-in function `id()` returns the identity of an object as an integer. This integer usually corresponds to the object’s location in memory, although this is specific to the implementation. The `is` operator compares the identity of two objects. The built-in function `type()` returns the type of an object. For example:

    # Compare two objects
    def compare(a,b):
        print 'The identity of a is ', id(a)
        print 'The identity of b is ', id(b)
        if a is b:
            print 'a and b are the same object'
        if a == b:
            print 'a and b have the same value'
        if type(a) is type(b):
            print 'a and b have the same type'

The type of an object is itself an object. This type object is uniquely defined and is always the same for all instances of a given type. Therefore, the type can be compared using the `is` operator. The standard module `types` contains the type objects for all the built-in types and can be used to perform type-checking. For example:

    import types
    if type(s) is types.ListType:
        print 'Is a list'
    else:
        print 'Is not a list'

When comparing object types in which user-defined classes are involved, it may be better to use the `isinstance()` function as described in Chapter 7, “Classes and Object-Oriented Programming.” The `isinstance(``s` `, C)` function correctly detects instances `s` of classes descended from the class `C`, as well as instances of `C` itself.

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