isinstance, and when to inherit
🌍 In real life. A puppy is a dog, and a dog is an animal, so a puppy is an animal too. Family trees can be more than two levels deep, and the lookup tower just gets taller. isinstance(obj, Class) asks "is this object one of these, or one of its children?"
The idea in one sentence: isinstance(obj, Class) is True for objects of that class and of its children, and you should inherit only when "child is a parent" is true; otherwise keep one object inside another.
Its words:
isinstance(obj, Class): "is this object one of these, or one of its children?"- is-a: a puppy is a dog → inheritance
- has-a (composition): a car has an engine → an attribute holding an
Engineobject
class Animal:
pass
class Dog(Animal):
pass
class Puppy(Dog):
pass
class Cat(Animal):
pass
bit = Puppy()
print(isinstance(bit, Puppy), isinstance(bit, Dog), isinstance(bit, Animal))
print(isinstance(bit, Cat))
print(issubclass(Puppy, Animal), issubclass(Cat, Dog))When should you inherit? Ask the "is-a" question:
- a bus is a vehicle → inheritance fits:
class Bus(Vehicle) - a car has an engine → it doesn't: the car should keep an
Engineobject as an attribute
Keeping one object inside another is called composition. It's often the better choice: an engine is not a kind of car, so a car shouldn't be an engine.
class Engine:
def __init__(self, power):
self.power = power
def start(self):
return "Vroom! (" + str(self.power) + " hp)"
class Car:
def __init__(self, model, power):
self.model = model
self.engine = Engine(power) # a car HAS an engine
def start(self):
return self.model + ": " + self.engine.start()
print(Car("Corolla", 140).start())Why prefer composition when unsure? A deep family tree ties classes together: a change high up ripples into every child. An object kept as an attribute can be swapped (a car with an electric engine) without touching the car class.
Mistakes and edge cases.
- type(x) == Parent for a child.
type(puppy) == Animalis False even though a puppy is an animal;isinstance(puppy, Animal)is True. - Inheriting for has-a.
class Car(Engine)would make a car "be" an engine, with all its methods. - Checking isinstance everywhere. If you find yourself asking "which class is this?" before every call, polymorphism (Lesson 22.3) is usually the better design.
Quiz
What does this print?
class Vehicle: pass class Bus(Vehicle): pass b = Bus() print(isinstance(b, Vehicle), isinstance(b, Bus))What does this print?
class Vehicle: pass class Bus(Vehicle): pass print(isinstance(Vehicle(), Bus))A
Librarykeeps manyBookobjects. Which design fits best?- Library has a list attribute of Book objects (composition)
- class Library(Book)
- class Book(Library)
What does this print?
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass pets = [Dog(), Cat(), Dog()] print(sum(1 for p in pets if isinstance(p, Dog)))What does this print?
class Battery: def __init__(self): self.level = 100 class Phone: def __init__(self): self.battery = Battery() p = Phone() p.battery.level = p.battery.level - 30 print(p.battery.level)A puppy is an animal, so this should print True. It prints False. Which line has the mistake?
class Animal: pass class Puppy(Animal): pass p = Puppy() print(type(p) == Animal)
Coding tasks
Animal,DogandCatare written for you. Writecount_dogs(animals)that returns how many of the animals are Dogs, usingisinstance.Engineis written for you. Write a classCar(model, power)that has an Engine (storeEngine(power)asself.engine) and a methodstart()returning"<model>: "followed by the engine'sstart().