Inheritance in Python
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
d = Dog()
[Link]()
Step-by-step explanation
1. class Animal:
o Defines a new class named Animal. A class is a blueprint for
creating objects. At this moment Python creates a class object
Animal and stores it in the current namespace.
2. def sound(self): (inside Animal)
o Defines an instance method called sound for the Animal class.
o The method expects one argument, conventionally named self,
which will refer to the instance that calls the method.
o The body: print("Animal makes a sound") — what happens when
this method runs.
3. class Dog(Animal):
o Defines a new class named Dog that inherits from Animal.
o Inheritance means Dog gets all attributes and methods from Animal
unless it overrides them. Python creates the Dog class object and
records that its base class is Animal.
4. def sound(self): (inside Dog)
o Defines a method with the same name (sound) in Dog. This is
method overriding: the Dog version replaces (overrides) the Animal
version for Dog instances. Its body prints "Dog barks".
5. d = Dog()
o Creates an instance/object of the Dog class.
o Python allocates memory for the new object d and sets its internal
class pointer to Dog.
o d is now an object whose type is Dog. Because Dog inherits from
Animal, d also has access to anything defined on Animal (unless
overridden).
6. [Link]()
o Method call on the instance d. Here’s what Python does internally:
▪ Look up sound on the instance d → finds nothing directly on
the instance, so it looks on the class Dog.
▪ It finds [Link] (the overridden method). Because Dog
defines sound, Python uses this method — dynamic dispatch
/ polymorphism in action.
▪ Python creates a bound method by binding d to [Link] so
that self inside the method will refer to d.
▪ Calls the bound method: inside the method self → d. The
method runs print("Dog barks").
7. Output produced
8. Dog barks
Extra notes / variations
• If Dog did not define sound, the lookup would continue to Animal and
[Link] would run, printing "Animal makes a sound".
• self is just a reference name; you can call it anything, but conventionally
it’s self. It gives the method access to the instance’s attributes.
• This demonstrates two OOP ideas:
o Inheritance: Dog inherits from Animal.
o Polymorphism / Method overriding: Dog provides its own sound()
implementation that replaces the parent’s for Dog objects.