We can probably guess what types those attributes should be. Brand and model are strings, and year is an integer. But what type should the engine be? Python has no built-in
Engine type, so here’s an opportunity for composition.
Now, we can say that our car’s
.engine attribute should be of type
Engine, meaning that the
.engine attribute must be set to a valid
Engine object. Because the
Car will have a valid
Engine object at the time it’s created, we can add some code in the car’s
.turn_on() method that literally calls the
.ignite() method in the car’s
We can even access the
Engine from a more global scope. For example, we can create a
Car object called
my_car, supplying a valid
Engine object for its
.engine attribute, and then get to the
.weight of that
Engine from the global scope by saying
my_car.engine.weight. Once again, I’ve prepared a few questions to test your understanding, so go ahead and pause the video and try your best at answering them.
The first question asks, “What is the type of the
.engine attribute?” That is simply
Engine. Remember, a class’s attributes are simply variables that objects instantiated from the class keep track of.
We can name variables virtually anything, and that’s completely independent of the variable’s type. I could have called the
.xyz, or anything you could normally name a variable.
The only way we can tell the type of the
.engine attribute in this diagram is because I drew a big arrow that says part of from the
Engine class to the bolded word engine. In a later video, you’ll learn about a more formal approach to diagramming these classes.
Next, I asked, “Does the
.accelerate() method have access to the
.efficiency attribute?” Here, the answer is yes. Remember, the methods you can call on an object have access to the attributes of that object.
This means that, in the last example,
Car was the composite class that was made up of an
Engine component. In the next video, you’ll see some examples of how inheritance is used in various parts of the Python language.
Become a Member to join the conversation.