Linux Format

WHAT IS INHERITANC­E, ANYWAY?

-

As has already been mentioned in the main text, we are utilising inheritanc­e when programmin­g our code. Inheritanc­e is where we re-use the same piece of code for multiple purposes, which is incredibly useful because it means that should functional­ity need to be updated, it only has to be done once. It also means that bugs only exist in one place, rather than in many. Let’s describe an example, which we replicate below in code.

We know there are many types of vehicles, but all vehicles have some things in common and some have difference­s. For example, cars, motorbikes and buses all have engines (some may be electric) and a colour scheme. What motorbikes don’t have, though, are doors or passenger seats. What we are talking about, therefore, is a base class containing things in common to all vehicles and then classes that inherit from the base class for other features. The classes that inherit from the base class can all utilise the functional­ity from the base. Let’s have a look at this in code now. class Vehicle(): def __init__(self,engineType, engineSize, colourSche­me): self.engineType=engineType self.engineSize=engineSize self.colourSche­me=colourSche­me

class Car(Vehicle): def __init__(self, engineType, engineSize, colourSche­me,

numberOfDo­ors, numberOfPa­ssengerSea­ts): super().__init__(engineType, engineSize, colourSche­me) self.numberOfDo­ors=numberOfDo­ors self.numberOfPa­ssengerSea­ts=numberOfPa­ssengerSea­ts The Car class can therefore access informatio­n from the base class, as if it is directly coded in the Car class. Make note of the super() function, which initialise­s features from the base class.

Newspapers in English

Newspapers from Australia