Composing With Classes
How do you combine classes together into systems? The first way you’re going to look at is with composition. Take a look at this class. It’s a
Point class that represents a point in two-dimensional space using the Cartesian coordinate system. You have your class definition, you have your constructor method, and you’re assigning some attributes in the constructor, your
.y position in space.
A class like this can make information easier to handle. It allows you to reference the values with labels like
.y and can be better than having the X and Y coordinates in a list, for instance, where there is no immediate indication as to what they represent.
And in that, you’re setting the points that were passed in in the constructor. You can imagine that the argument would be passed in as a list. So then as an attribute of the
Shape instance, you’d have
.points, which would be a list of points.
We’re going to split this up onto various lines so that it looks neater. And each item in the list will be a
Point. Let’s start off with a point at the origin, and then we’ll have another point at, say,
So here everything’s happening in this one expression. You are instantiating a
Shape, and the
Shape() constructor needs one argument, which is the
points. We’re starting a list, and then within that list, each element of that list is an instantiation of a
03:29 And that is an example of composition. You’re using one class as a way to build the attributes of other classes. This doesn’t have to be limited to one class being an attribute of another class that takes it in.
03:45 You can have many low-level classes that stand quite independently, and then you can have one or more classes that group them together into higher-level classes. As the name suggests, composition is something of a creative activity.
Then you can instantiate a new
Shape object and then pass in, in a list, the four variables that you just defined. Then you’ll see that
square is a
Shape, is an instantiated
Shape, and the
.points attribute of the
square contain four instances of the
Become a Member to join the conversation.