The concept of inheritance is focused entirely on code reuse and maintainability of code.
Inheritance is a fundamental part of object-oriented design that allows one class (the subclass) to inherit attributes and methods of another class (the superclass).
Inheritance in Python
A cat is an animal, so we can define an Animal superclass as shown below:
class Animal: # An animal class type = "" name = "" def __init__(self, type, name): self.type = type self.name = name def act(self): print("Doing something") def getName(self): return self.name
Now, we can define a Cat class for our cat:
class Cat (Animal): # A cat class name = "" def __init__(self, name): self.type = "Cat" self.name = name def act(self): print("Meow")
Now in the same program, instantiating a new cat and using the act
method on
the newly instantiated cat, we should get the word Meow
on
the screen.
c = Cat("Gismo") c.act() print(c.getName())
This is simply overwriting the act
method defined in the Animal
superclass
with its own derivation of it and then utilising the getName
method
from the superclass to get the name property of the instance.