Class Inheritance in Object-Oriented Programs

Programming Paradigm Concepts

Eleanor Thomas

Senior Data Analytics Engineer

Class inheritance in object-oriented programming

  • Class inheritance: when one class "inherits" methods and attributes from another, parent class
  • Example:
    • Poodle class inherits from Dog (and has curly hair)
    • Dog class inherits from Pet (and "barks")
    • Pet class inherits from Animal
  • No limit to the number of layers of inheritance, but more is not always better

Group of pets

Programming Paradigm Concepts

Class inheritance example

class Dog():
    def __init__(self, name):
        self.name = name
    def bark(self):
        print("Arf!")

lacy = Dog("Lacy")
lacy.bark()
class Pet():
    def __init__(self, name):
        self.name = name

class Dog(Pet): def bark(self): print("Arf!")
lacy = Dog("Lacy") lacy.bark()
Programming Paradigm Concepts

Class inheritance example continued

class Cat(Pet):
    def meow(self):
        print("Meow!")

class Horse(Pet): def neigh(self): print("Neigh!")
fluffy = Cat("Fluffy")
fluffy.meow()
Meow!
midnight = Horse("Midnight")
midnight.neigh()
Neigh!

All of the following produce Errors!

fluffy.neigh()
fluffy.bark()
midnight.meow()
Programming Paradigm Concepts

Let's practice!

Programming Paradigm Concepts

Preparing Video For Download...