Skip to content
IT Vizag
← Objects & Classes

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

Inheritance

Lesson 5 of 10 · 2 min read

Build new classes from existing ones, and when not to.

🎬 Video version coming soon — read it now

Inheritance lets a new class reuse an existing class and add or change parts of it. The new class is the child (subclass); the original is the parent (base class).

🔒 Code example: sign up free (above) to unlock it.

What happened

  • class Manager(Employee) means a Manager is an Employee. It gets describe and everything else for free.
  • super().__init__(...) runs the parent's constructor so name and salary are set up properly.
  • Manager overrides annual_pay with its own version, which still uses the parent's via super().
  • The loop calls describe() on each person without checking their type, and each one computes its pay correctly. That's called polymorphism: same method name, behaviour suited to each class.

isinstance

🔒 Code example: sign up free (above) to unlock it.

When NOT to inherit

Use inheritance only for a genuine "is a" relationship. A Manager is an Employee. But a Car is not an Engine; a car has an engine. For "has a", store one object inside another (composition):

🔒 Code example: sign up free (above) to unlock it.

Deep inheritance chains (A → B → C → D → E) become hard to follow. Most good Python code uses shallow inheritance, one or two levels, and lots of composition.

Tip: In interviews, "prefer composition over inheritance" is a phrase worth knowing, along with an example like the Car and Engine.

In one line

A child class inherits a parent's attributes and methods, can override them and call the parent with super(); use it only for real "is a" relationships.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend