4.3 Instances
The purpose of a class is to create instances of it. We can use this for something as simple as implementing what are called structs or records in other languages. For example, class point: pass declares a class object called point. The pass statement executes no operation. We need it because the syntax requires a class statement to have a suite of one or more statements as a body.
We can create an instance of the class point by calling point() as a function:
>>> p=point()
We can then assign values to attributes of the point using the dotted notation and access them the same way:
>>> p.x=1 >>> p.y=2 >>> p.x 1 >>> p.y 2
But when we create a point, it doesn't start with any attributes.
>>> q=point() >>> q.x Traceback (innermost last): File "<stdin>", line 1, in ? AttributeError: x
This is a major difference between instances of classes in Python and structs or records in most other languages. In most languages, you have to declare the attributes (fields, members) of the structs or records. In Python, the first assignment to an attribute creates it. The attributes are kept in the __dict__ dictionary of the instance:
>>> p.__dict__ {'x': 1, 'y': 2}
Assignment to an attribute is equivalent to an assignment to the attribute name in the __dict__ dictionary.
A problem with Python then is, "What if we want the instance of the class to start off with a set of attributes?" To do this, we can provide an initialization procedure in our declaration of the class that will be called when an instance is created:
>>> class point: ... def __init__(self): ... self.x=0 ... self.y=0 ... >>> q=point() >>> q.x 0
Here we have redeclared point, replacing pass with a function definition. The function name is __init__. When Python creates an instance of the point, it calls the __init__(self) function and passes it a reference to the point it has just created. Function __init__(self) then assigns zero to both attributes x and y via the parameter self. Just as with the assignments from outside, these assignments create the attributes.
The __init__() function is an initializer. Although it is called by Python just after the instance is created to initialize it, you can call it again at any later time to reinitialize the object.
If you want to know what attributes are defined in an instance of a class, you can use the dir(), as in "directory," function:
>>> dir(p) ['x', 'y']