📡 You're offline — showing cached content
New version available!
Quick Access
Python Intermediate

Python OOP: Inheritance, Polymorphism and Dunder Methods

Master Python OOP — class inheritance, super(), method overriding, polymorphism, and dunder methods for operator overloading and protocol support.

EzyCoders Admin December 4, 2025 11 min read 0 views
Python OOP Inheritance Polymorphism Dunder Methods
Share: Twitter LinkedIn WhatsApp

Python OOP: Inheritance and Dunder Methods

Python's OOP model is elegant and flexible. Dunder methods let your objects integrate seamlessly with Python's built-in features.

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

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

    def __repr__(self): return f"Animal({self.name!r})"
    def __str__(self):  return self.name

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name, 'Woof')
        self.breed = breed

    def speak(self):  # override
        return f"{super().speak()}! (excited)"

animals = [Dog('Rex','Lab'), Animal('Cat','Meow')]
for a in animals: print(a.speak())  # polymorphism

Dunder Methods

class Vector:
    def __init__(self, x, y):
        self.x = x; self.y = y

    def __add__(self, o):   return Vector(self.x+o.x, self.y+o.y)
    def __mul__(self, s):   return Vector(self.x*s, self.y*s)
    def __len__(self):      return 2
    def __getitem__(self, i): return (self.x, self.y)[i]
    def __iter__(self):     yield self.x; yield self.y
    def __eq__(self, o):    return self.x==o.x and self.y==o.y
    def __repr__(self):     return f"Vector({self.x}, {self.y})"

v1 = Vector(1, 2)
print(v1 + Vector(3,4))  # Vector(4, 6)
x, y = v1                 # unpacking via __iter__

Q: Difference between __str__ and __repr__?

__repr__ is for developers — unambiguous, shows how to recreate the object. __str__ is for end users — readable and friendly. If only __repr__ defined, Python uses it for __str__ too.

EzyCoders Admin
Written by
EzyCoders Admin

Team Lead and Full-Stack Developer with experience in PHP, JavaScript, SQL, DSA, and System Design. Passionate about software engineering, scalable web technologies, and helping developers prepare for coding interviews and tech careers through practical tutorials and professional guidance.

Comments (0)

No comments yet. Be the first!

Leave a Comment