def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self,text):
self.description = text
def authorName(self,text):
self.author = text
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
If we wanted to define a new class, lets say a square, based on our previous Shape class, we would do this:
Code Example 7 - Using inheritance
class Square(Shape):
def __init__(self,x):
self.x = x
self.y = x
It is just like normally defining a class, but this time we put in brackets after the name, the parent class that we inherited from. As you see, we described a square really quickly because of this. That's because we inherited everything from the shape class, and changed only what needed to be changed. In this case we redefined the __init__ function of Shape so that the X and Y values are the same.
Let's take from what we have learnt, and create another new class, this time inherited from Square. It will be two squares, one immediately left of the other:
Code Example 8 - DoubleSquare class
# The shape looks like this:
# _________
#| | |
#| | |
#|____|____|
class DoubleSquare(Square):
def __init__(self,y):
self.x = 2 * y
self.y = y
def perimeter(self):
return 2 * self.x + 3 * self.y
This time, we also had to redefine the perimeter function, as there is a line going down the middle of the shape. Try creating an instance of this class. As a helpful hint, the idle command line starts where your code ends - so typing a line of code is like adding that line to the end of the program you have written.
Pointers and Dictionaries of Classes
Thinking back, when you say that one variable equals another, e.g. variable2 = variable1, the variable on the left-hand side of the equal-sign takes on the value of the variable on the right. With class instances, this happens a little differently - the name on the left becomes the class instance on the right. So in instance2 = instance1, instance2 is 'pointing' to instance1 - there are two names given to the one class instance, and you can access the class instance via either name.
In other languages, you do things like this using pointers, however in python this all happens behind the scenes.
The final thing that we will cover is dictionaries of classes. Keeping in mind what we have just learnt about pointers, we can assign an instance of a class to an entry in a list or dictionary. This allows for virtually any amount of class instances to exist when our program is run. Lets have a look at the example below, and see how it describes what I am talking about:
Code Example 9 - Dictionaries of Classes
# Again, assume the definitions on Shape,
# Square and DoubleSquare have been run.
python tutorials
Start from the beginning
