PYTHON LESSON 22 OF 32

Inheritance & composition

Inheritance creates a specialized class from another class. Composition gives an object another object to work with. Use inheritance for an is-a relationship and composition for a has-a relationship.

हिन्दी में समझें

इनहेरिटेंस पुरानी क्लास का विशेष रूप बनाता है। कंपोज़िशन में वस्तु के अंदर दूसरी वस्तु होती है। is-a के लिए इनहेरिटेंस, has-a के लिए कंपोज़िशन सोचें।

अभ्यास: Animal की Cat उपक्लास बनाएँ जिसका speak Meow! लौटाए और प्रिंट करें।

Hinglish mein samjhein

Inheritance ek class ka specialized version banata hai. Composition mein object ke paas doosra object hota hai. is-a vs has-a soch kar choose karo.

Practice: Animal ki Cat subclass banao; speak Meow! return kare aur print ho.

A small Python example

class Animal:
    def speak(self):
        return "A sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

print(Dog().speak())

The browser playground runs real Python with Pyodide. Use sample variables instead of interactive input(). Browser package support differs from desktop Python.

Try this example in the Python playground →

Practise this idea

Create Cat as an Animal subclass whose speak returns Meow!, then print it.

Check answer & explanation
class Animal:
    def speak(self):
        return "A sound"

class Dog(Animal):
    def speak(self):
        return "Woof!"

print(Dog().speak())
class Cat(Animal):
    def speak(self):
        return "Meow!"
print(Cat().speak())

Cat inherits from Animal and overrides speak(). Calling Cat().speak() selects the subclass implementation.

Stuck in the course? Choose Check answer for either the challenge or quiz. Read the explanation and continue to the next lesson at your own pace.

Check your understanding

Dog is an Animal. This is…

  1. Inheritance
  2. A list
  3. JSON
Check the quiz answer

Inheritance

Dog specializes Animal and overrides speak().

References & corrections

Use the official Python documentation for full language rules. Read how these lessons are made and checked. Found a mistake? Report it to Excel Keys with this lesson URL and a reproducible example.

FROM LEARNING TO BUSINESS RESULTS

Need a dashboard for your team?

Excel Keys designs custom Excel and HTML dashboards around your own KPIs and Excel files. They run offline in the browser, so your data stays on your computer.