Python 3D Academyবাংলা

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 Engine object
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 Engine object 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) == Animal is 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

  1. What does this print?

    class Vehicle:
        pass
    
    class Bus(Vehicle):
        pass
    
    b = Bus()
    print(isinstance(b, Vehicle), isinstance(b, Bus))
  2. What does this print?

    class Vehicle:
        pass
    
    class Bus(Vehicle):
        pass
    
    print(isinstance(Vehicle(), Bus))
  3. A Library keeps many Book objects. Which design fits best?

    • Library has a list attribute of Book objects (composition)
    • class Library(Book)
    • class Book(Library)
  4. 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)))
  5. 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)
  6. 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

  1. Animal, Dog and Cat are written for you. Write count_dogs(animals) that returns how many of the animals are Dogs, using isinstance.

  2. Engine is written for you. Write a class Car(model, power) that has an Engine (store Engine(power) as self.engine) and a method start() returning "<model>: " followed by the engine's start().