Page 3 of 5
Moving on to more traditional object-oriented facilities brings us to the class statement.
You can define a class complete with variables and functions and create instances of the class by assignment. This sounds all too easy and I have to admit that it really is easy. The only minor complication is that you have to use the keyword “self” as a reference to the particular instance of the class. Consider, for example:
This defines a class called point which has two methods – setpos and display. Each of these has the default parameter “self” included. The methods use “self” to qualify any variables that are specific to the instance of the class.
If you now create an instance of the class using:
you can refer to methods using the usual dot a.method() notation. For example,
If you use a class definition of the form:
then the new class inherits all of the methods defined in superclass. For example:
defines a new class called complexpoint and inherits all of the methods defined in point.
You can, of course, define new methods and override existing methods.
If a method cannot be found in the class’s definition the superclass definition is searched. If the method cannot be found in the superclass then any super-superclass that might exist is searched and so on until a definition is found or an error is generated. You can also arrange to call the inherited method directly using the class name as the first parameter of the call. In fact all method calls are translated from:
and the first parameter is “self”. You can call instance methods directly using this form. For example:
is entirely equivalent to:
Finally it is worth knowing that operator overloading is supported using a range of standard method names.
For example, if you want to define an addition for points then you need the following method:
Now you can write:
where x and y are point objects. Notice that z isn’t a point object but a tuple a special sort of list. If you want to return a point object you have to use:
Overriding operators might not seem like something you want to do but after using Python for a while I can assure you that you will – if only to write constructors.
The __init__ operator is the objects constructor and if you overwrite it you can define a non-default constructor. For example, if you include:
in the point definition you can now initialise a point using:
and if you don’t specify a value then a (0,0) point is constructed by default. There is also a destructor operator, indexing operator, string slicing operator and so on, all of which can be overloaded.