next up previous contents
Next: Method objects Up: A first look Previous: Class objects

Instance objects

Now what can we do with instance objects? The only operations understood by instance objects are attribute references. There are two kinds of valid attribute names.

The first I'll call data attributes. These correspond to ``instance variables'' in Smalltalk, and to ``data members'' in C++. Data attributes need not be declared; like local variables, they spring into existence when they are first assigned to. For example, if x in the instance of MyClass created above, the following piece of code will print the value 16, without leaving a trace:

        x.counter = 1
        while x.counter < 10:
                x.counter = x.counter * 2
        print x.counter
        del x.counter

The second kind of attribute references understood by instance objects are methods. A method is a function that ``belongs to'' an object. (In Python, the term method is not unique to class instances: other object types can have methods as well, e.g., list objects have methods called append, insert, remove, sort, and so on. However, below, we'll use the term method exclusively to mean methods of class instance objects, unless explicitly stated otherwise.)

Valid method names of an instance object depend on its class. By definition, all attributes of a class that are (user-defined) function objects define corresponding methods of its instances. So in our example, x.f is a valid method reference, since MyClass.f is a function, but x.i is not, since MyClass.i is not. But x.f is not the same thing as MyClass.f --- it is a method object, not a function object.



guido@cwi.nl