Skip to main content

OOP for Python

Absolutely! Here's a practical set of Python OOP code examples for each item in your 🧱 Object-Oriented Programming (OOP) checklist β€” perfect for review or muscle-memory practice.


🧱 Object-Oriented Programming (OOP) in Python β€” With Code Examples


βœ… 1. Create a class with __init__()

class Dog:
    def __init__(self, name):
        self.name = name

d = Dog("Fido")
print(d.name)  # Fido

βœ… 2. Add a method to the class

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return f"{self.name} says woof!"

d = Dog("Rex")
print(d.bark())  # Rex says woof!

βœ… 3. Use @property for a read-only attribute

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def area(self):
        return 3.14 * self._radius ** 2

c = Circle(3)
print(c.area)  # 28.26
# c.area = 50  # ❌ Error: can't set attribute

βœ… 4. Inherit from another class

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

class Dog(Animal):
    def speak(self):
        return "Bark"

d = Dog()
print(d.speak())  # Bark

βœ… 5. Override a method

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

class Cat(Animal):
    def speak(self):
        return "Meow"

c = Cat()
print(c.speak())  # Meow

βœ… 6. Use super() to call base class method

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

class Dog(Animal):
    def speak(self):
        base = super().speak()
        return base + " + Bark"

d = Dog()
print(d.speak())  # Some sound + Bark

βœ… 7. Use __repr__() or __str__()

class Dog:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f"Dog('{self.name}')"

    def __str__(self):
        return f"My dog's name is {self.name}"

d = Dog("Buddy")
print(repr(d))  # Dog('Buddy')
print(str(d))   # My dog's name is Buddy

Absolutely! Here's the full ChatGPT response on polymorphism, polished and formatted so you can save it, review it, or turn it into a markdown or flashcard:


🧱 What is Polymorphism in Python?

πŸ” Definition:

Polymorphism means "many forms" β€” the same function or method behaves differently depending on the object it’s acting on.


πŸ’‘ Real-World Analogy:

  • You call draw() on a Circle, Square, or Triangle and each one handles it differently.

  • You don’t care how it draws β€” you just know the object will handle it correctly.


πŸ§ͺ Python Polymorphism Example 1: Method Overriding

This is classic runtime polymorphism through inheritance:

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

class Dog(Animal):
    def speak(self):
        return "Bark"

class Cat(Animal):
    def speak(self):
        return "Meow"

animals = [Dog(), Cat()]

for animal in animals:
    print(animal.speak())  # Bark, Meow

βœ… You call the same method (speak()), but each class handles it differently.


πŸ¦† Python Polymorphism Example 2: Duck Typing

Python doesn’t require a shared parent class β€” it just cares if the object has the right method.

class Bird:
    def fly(self):
        print("Flapping wings")

class Plane:
    def fly(self):
        print("Engines on")

def lift_off(flier):
    flier.fly()

lift_off(Bird())   # Flapping wings
lift_off(Plane())  # Engines on

βœ… As long as the object has a .fly() method, it can be passed in β€” β€œif it quacks like a duck...”


🧠 TL;DR:

Concept Meaning
Polymorphism Same method name, different behavior
Method override Subclasses implement their own version
Duck typing Type doesn't matter, behavior does
Benefit Cleaner, extensible, decoupled code

Would you like me to export this explanation as a .md, .txt, or add it to a reference doc for your interview prep?