Skip to content
wannacode

What is it really?

Problem

Only some of them can charge

A company has a fleet of regular and electric cars. Every evening the electric ones need to be charged. ElectricCar inherits from Car and adds charge(), so they are all in one list:

fleet = [
Car("Skoda"),
ElectricCar("Tesla", 35),
Car("Dacia"),
ElectricCar("Nissan", 60),
]
for c in fleet:
c.charge()

The program starts and stops at the very first car, "Skoda": AttributeError: 'Car' object has no attribute 'charge'. It never gets to the electric ones.

A regular car really cannot be charged. You have to ask each car: "are you electric?"

The idea

Ask the object what it is

for c in fleet:
if isinstance(c, ElectricCar):
c.charge()
print(f"{c.brand}: charged to {c.battery}%")
Output
Tesla: charged to 100%
Nissan: charged to 100%

isinstance(c, ElectricCar) asks the object c points to: "are you an ElectricCar?" and gives True or False. This is called a type check.

You do not need a new variable. In Python variables have no type, so there is nothing to convert: once the check is true, c points to an electric car and c.charge() works. The cars stay the same.

for c in fleet:
if isinstance(c, ElectricCar):
c.charge()
print(f"{c.brand}: charged to {c.battery}%")
Step by step, in words
  1. fleet is a list: 2 regular and 2 electric cars.
  2. c points to Skoda: isinstance says "no". The body of the if is skipped.
  3. c points to Tesla: isinstance says "yes". No new variable is needed: c.charge() charges the same car.
  4. c points to Dacia: isinstance says "no". The body of the if is skipped.
  5. c points to Nissan: isinstance says "yes". No new variable is needed: c.charge() charges the same car.
  6. The cars do not change. The check only asks the object what it is.

Try it

Is it a car?

What will the program print?

c = ElectricCar("Tesla", 35)
d = Car("Skoda")
print(isinstance(c, Car))
print(isinstance(c, ElectricCar))
print(isinstance(d, ElectricCar))
Answer

The idea

Other forms you will run into

Besides isinstance you will run into two more ways to ask an object:

c = fleet[1]
print(type(c) is ElectricCar)
print(type(c) is Car)
print(isinstance(c, Car))
print(hasattr(c, "charge"), hasattr(fleet[0], "charge"))
Output
True
False
True
True False
  • type(c) is ElectricCar asks "is it exactly an ElectricCar?". For the electric car type(c) is Car is False, while isinstance(c, Car) is True. You almost always want isinstance: it accepts child classes too.
  • hasattr(c, "charge") does not ask about the class, only whether the object has such a method. This is a check against a contract, as with interfaces: any class with charge() passes.
More precisely, if you are curious
  • The check is always false for None, and isinstance also accepts several classes at once, in parentheses: it is true if the object belongs to any of them.
print(isinstance(None, Car))
print(isinstance(fleet[1], (Car, ElectricCar)))
Output
False
True
  • The check works with contracts too: isinstance(a, Swimmable) asks whether the object's class has taken on the abstract class Swimmable.

Try it

Find the bug

The program counts the regular and the electric cars. The fleet has two of each, but it prints:

Output
Regular: 4, electric: 0

Which line is the bug on?

Pick the line with the bug.

The idea

A check or a method?

You want to print what each car runs on. A type check can do it:

for c in fleet:
if isinstance(c, ElectricCar):
print(f"{c.brand}: electricity")
else:
print(f"{c.brand}: gasoline")

But this is the salary with an if per role from the lesson on polymorphism. Every car has an energy source, just a different one. That is a job for a method in Car, overridden in ElectricCar:

# in Car
def energy(self):
return "gasoline"
# in ElectricCar
def energy(self):
return "electricity"
for c in fleet:
print(f"{c.brand}: {c.energy()}")
Output
Skoda: gasoline
Tesla: electricity
Dacia: gasoline
Nissan: electricity

Tomorrow a hybrid car comes along. With the method, you write a new class. With the checks, you hunt down every if in the program.

The rule:

  • Every object does it, each in its own way: a method in the parent, and overriding.
  • Only some objects can do it (charging, pedaling): a type check.

Try it

What is missing?

for c in fleet:
    if (c, ElectricCar):
        c.charge()

In short

The four pillars of OOP

With this lesson you have finished the modules "Classes and objects" and "Inheritance and polymorphism". Object-oriented programming rests on four ideas. You already use all of them:

  • Encapsulation. The object's data is hidden, and from outside you reach it only through methods that guard the rules. Account keeps the balance with an underscore and offers only deposit() and withdraw(). Encapsulation
  • Inheritance. What is shared sits in one place, the parent, and the child adds its own. Manager is an Employee with a bonus. Inheritance
  • Polymorphism. One call, different behavior depending on the object. e.monthly_pay() in one loop works out the pay of an employee, a manager and an intern. Polymorphism
  • Abstraction. You say what the object must be able to do, and each class decides how. The abstract Shape promises an area, the Payable contract promises an amount to pay. Abstract classes, Interfaces

Exercise

What is it really?

Solve these in your editor.

1. Parking lot. A list of regular and family cars (FamilyCar inherits from SimpleCar). For each one, print its type. Watch the order of the checks.

Output
This is a SimpleCar
This is a FamilyCar
This is a SimpleCar

2. Dances. A list of regular and breakdance moves. For the breakdance moves, also print the complexity. Only BreakDanceMove has it, so ask for it after the check.

Output
moonwalk: DanceMove
windmill: BreakDanceMove, complexity 8
salsa: DanceMove

3. Fleet. Take Car and ElectricCar from the exercise in the "Inheritance" lesson. In a list, put a "Skoda" with 40 L, a "Tesla" with efficiency 5, a "Dacia" with 5 L and a "Nissan" with efficiency 4. Each one drives 100 km: the electric ones with drive_electric, the rest with drive. Then print the kilometers and the fuel or the battery.

Output
Skoda: 100 km, fuel 30 L
Tesla: 100 km, battery 80%
Not enough fuel for 100 km
Dacia: 0 km, fuel 5 L
Nissan: 100 km, battery 75%

4. Zoo. An abstract class Animal with sound(), and child classes Cat, Dog and Fish. Only Fish implements Swimmable with swim(). In a loop over the animals, call each one's sound, and for the ones that can swim, also call swim().

Output
Meow, meow!
Woof, woof!
The fish is silent.
The fish swims.

More tasks

  • Pedals. In the exercise from the "Abstract classes" lesson, garage[0].pedal() stopped the program, because there is no bicycle there. Fix it with a type check: in the loop over the vehicles, every vehicle starts, and only the bicycle also pedals.
  • Payments by kind. From the "Interfaces" lesson: the payments list holds employees and invoices. Print the total for salaries and the total for invoices separately. For Ivan, Maria and the two invoices: €5,500 in salaries and €2,140 in invoices.

Test

Check yourself

1. isinstance(c, ElectricCar) is true. How do you charge the car?
2. c points to an ElectricCar. What is isinstance(c, Car)?
3. You check whether a car is a Car or an ElectricCar. In what order?
4. The program has many ifs like "if it is an ElectricCar, do one thing, otherwise do another". What does that tell you?
5. c points to a regular car. What happens at c.charge(), with no check before it?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·