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

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105086039026000243077235

### Class Instances

Instances of a class are created by calling a class object as a function. This creates a new instance and calls the `_ _init_ _()` method of the class (if defined). For example:

    # Create a few accounts
    a = Account("Guido", 1000.00)     # Invokes Account._ _init_ _(a,"Guido",1000.00)
    b = Account("Bill", 100000000000L)

Once created, the attributes and methods of the newly created instances are accessible using the dot (`.`) operator as follows:

    a.deposit(100.00)        # Call Account.deposit(a,100.00)
    b.withdraw(sys.maxint)   # Call Account.withdraw(b,sys.maxint)
    name = a.name            # Get account name
    print a.account_type     # Print account type

Internally, each instance is implemented using a dictionary that’s accessible as the instance’s `_ _dict_ _` attribute (described in detail in Chapter 3).This dictionary contains the information that’s unique to each instance. For example:

    >>> print a._ _dict_ _
    {'balance': 1100.0, 'name': 'Guido'}
    >>> print b._ _dict_ _
    {'balance': 97852516353L, 'name': 'Bill'}

Whenever the attributes of an instance are modified, these changes are made to the instance’s local dictionary. Within methods defined in the class, attributes are changed through assignment to the `self` variable as shown in the `_ _init_ _()`, `deposit()`, and `withdraw()` methods of `Account`. However, new attributes can be added to an instance at any time, like this:

    a.number = 123456    # Add attribute 'number' to a._ _dict_ _

Although the assignment of attributes is always performed on the local dictionary of an instance, attribute access is somewhat more complicated. Whenever an attribute is accessed, the interpreter first searches the dictionary of the instance. If no match is found, the interpreter searches the dictionary of the class object used to create the instance. If this fails, a search of base classes is performed. (See the later section “Inheritance” for details on base classes.) If this fails, a final attempt to find the attribute is made by attempting to invoke the `_ _getattr_ _()` method of the class (if defined). If this fails, an `AttributeError` exception is raised.

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