Skip to main content

How to Inherit from a Class in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

When a new class is a special kind of an existing one, it can inherit everything the existing class has and change only what's different. A Cat is an Animal, but it speaks its own way. This guide builds both classes, with real output from Python 3.15.2.

Syntax​

Syntax
class <ChildClass>(<ParentClass>):
def <method>(self):
... # replaces the parent's method of the same name
PartWhat it means
(<ParentClass>)The class to inherit from. The child gets all of its methods
A method with the parent's nameOverrides it: objects of the child class use this one

The Python tutorial: "Derived classes may override methods of their base classes."

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

Cat inherits __init__ from Animal and replaces only speak.

animals.py
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
return f"{self.name} makes a sound"


class Cat(Animal):
def speak(self):
return f"{self.name} says meow"


print(Animal("Generic").speak())
print(Cat("Tom").speak())
print(isinstance(Cat("Tom"), Animal))

The animals.py script in a macOS-style code window: class Animal with init and speak, class Cat(Animal) with its own speak, then prints of Animal("Generic").speak(), Cat("Tom").speak() and isinstance(Cat("Tom"), Animal).

Step 2: Run It​

Terminal
uv run python animals.py
Output
Generic makes a sound
Tom says meow
True

The script's output in a terminal: Generic makes a sound, Tom says meow and True.

Cat("Tom") got its name from Animal's __init__ and spoke with its own speak. isinstance confirms a cat is also an animal.

Common Mistakes​

MistakeWhat happensDo this instead
A child __init__ that doesn't call the parent'sThe parent's setup never runs: tom.name raised AttributeError: 'Cat' object has no attribute 'name'Call super().__init__(name) in the child's __init__
Repeating the parent's code in the childTwo copies to keep in stepInherit it, and override only what differs

Troubleshooting​

SymptomLikely causeFix
AttributeError: '...' object has no attribute ... on a child objectThe child's __init__ replaced the parent's without calling itAdd super().__init__(...)

FAQ​

How does the child add its own data?​

Give it an __init__ that calls the parent's first. With super().__init__(name) and self.indoor = indoor, Cat("Tom", indoor=True) had both: tom.name, tom.indoor printed Tom True.

What does super() return?​

The reference: "Return a proxy object that delegates method calls to a parent or sibling class of type." In practice, it lets the child call the parent's version of a method.

Conclusion​

class Cat(Animal) inherited Animal's __init__ and overrode speak, so Cat("Tom").speak() said Tom says meow. When the child needs its own __init__, call super().__init__(...) in it.

Additional Resources​