Coherent example¶
The points mentioned so far are the basics of using classes and objects in
Python. I will now illustrate these basics in a coherent example:
form.py
.
First, we create a base class:
1"""form module. Contains the classes Form, Square and Circle""" 2 3 4class Form: 5 """Form class: has method move""" 6 7 def __init__(self, x, y): 8 self.x = x 9 self.y = y 10 11 def move(self, deltaX, deltaY): 12 self.x = self.x + deltaX
- Line 7
The
__init__
method requires one instance (self
) and two parameters.- Lines 8 and 9
The two instance variables
x
andy
, which are accessed viaself
.- Line 10
The
move
method requires one instance (self
) and two parameters.- Lines 11 and 12
Instance variables that are set in the
move
method.
Next, create a subclass that inherits from the base class
Form
:16class Square(Form): 17 """Square Class:inherits from Form""" 18 19 def __init__(self, length=1, x=0, y=0): 20 super().__init__(x, y) 21 self.length = length
- Line 16
The class
Square
inherits from the classForm
.- Line 19
Square
’s__init__
takes one instance (self
) and three parameters, all with defaults.- Line 20
Square
’s__init__
usessuper()
to callForm
’s__init__
.
Finally, we create another subclass that also contains a static method:
27class Circle(Form): 28 """Circle Class: inherits from Form and has method area""" 29 30 circles = [] 31 pi = 3.14159 32 33 def __init__(self, diameter=1, x=0, y=0): 34 super().__init__(x, y) 35 self.diameter = diameter 36 self.__class__.circles.append(self) 37 38 def circumference(self): 39 return self.diameter * self.__class__.pi 40 41 @classmethod 42 def circumferences(cls): 43 """Class method to sum all circle circumferences."""
- Lines 29 and 30
pi
andcircles
are class variables forCircle
.- Line 34
In the
__init__
method, the instance inserts itself into thecircles
list.- Lines 37 and 38
circumferences
is a class method and takes the class itself (cls
) as a parameter.- Line 41
uses the parameter
cls
to access the class variablecircles
.
Now you can create some instances of the class Circle
and analyse them.
Since the __init__
method of Circle
has default parameters, you can
create a circle without specifying any parameters:
>>> import form
>>> c1 = form.Circle()
>>> c1.diameter, c1.x, c1.y
(1, 0, 0)
If you specify parameters, they are used to set the values of the instance:
>>> c2 = form.Circle(2, 3, 4)
>>> c2.diameter, c2.x, c2.y
(2, 3, 4)
When you call the move()
method, Python does not find a move()
method in
the Circle
class, so it goes up the inheritance hierarchy and uses the
move()
method of Form
:
>>> c2.move(5, 6)
>>> c2.diameter, c2.x, c2.y
(2, 8, 10)
You can also call the class method circumferences()
of the class Circle
,
either through the class itself or through an instance:
>>> form.Circle.circumferences()
9.424769999999999
>>> c2.circumferences()
9.424769999999999