Using Composition and Inheritance
It’s going to start with the
Point class. This is going to be our low-level class. And we’re also going to make use of the
Shape class that uses
.points as one of the attributes displaying composition.
So we’ve got composition in this model already, but we want to extend this model. Instead of just having
Shape, we want to have specific shapes. We want to have squares and triangles, for instance.
So now what do we want? One of the useful things about classes is that in the constructor method, you can create checks to make sure that the developer, which in many cases will mean yourself—and yes, you do need to protect yourself against yourself in programming—by creating a check. So let’s override the
.__init__() for now.
points is going to be a list—if
(len(points) != 4)—because a square has four points, right?—we’ll want to raise an exception, but we don’t want to raise just a bare exception.
01:52 That is considered bad practice because it doesn’t tell you anything about the exception. It just says, oh, this is an error. So let’s create a new exception in the way that is very common in Python.
So let’s just do it at the top here.
class. Let’s call this
WrongNumberOfPoints because we’re going have a bunch of shapes, and we’ll subclass that from the base
Exception class, and we’ll pass. So we’re just using everything from
Exception, but we’re giving it a new name.
And then we can just use this name here to raise that error if the number of points is not four. So say we pass in five points, that would suggest that it’s a pentagon and not a square, so we want that to give a
And then we can close the list and close brackets to complete the instantiation. And now if you look at
square, we can see that that’s a
Square object, and it will behave in the same way as the
Shape object, which contains an array of points.
04:16 Since we’re going to be checking for the number of points, like in a square has to have four, a triangle has to have three, we want this custom exception. So here is a quick example of inheritance, but that’s not the main example. The main example is the square.
Square class subclasses
Shape, and then it overrides the
.__init__() constructor. Within that, it checks whether the length of the
points list is
4, because a square has to have exactly four points. If it doesn’t, then it raises the
If that passes, then it assigns its own attribute to the
points list. You could extend that to a triangle, for instance. Pretty much the same thing, except you would check if it has three points instead of four.
That’s an example of using composition and inheritance within the same system. You’re using composition in the
.points attribute because the objects within the list of points are themselves classes that you created.
Become a Member to join the conversation.