Reading history

Python Polymorphism and Encapsulation (OOP)

4 min read 1 views

Learn polymorphism and encapsulation in Python: method overriding, duck typing, underscore naming, name mangling and @property validation.

Two more ideas complete the core of object-oriented programming. Polymorphism means one call can work on many types: shape.area() computes correctly whether the shape is a rectangle or a circle. Encapsulation means an object controls access to its own data, so it can reject bad values. This lesson shows both in Python, including the @property decorator and Python’s underscore naming rules.

In this lesson you will learn

  • How method overriding gives polymorphism
  • Polymorphism in built-ins like len() and +
  • What single and double leading underscores mean
  • How @property adds checks to an attribute
  • The four pillars of OOP in one table

Polymorphism

class Shape:
    def area(self):
        raise NotImplementedError

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h
    def area(self):
        return self.w * self.h

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        return round(3.14159 * self.r ** 2, 2)

for shape in [Rectangle(3, 4), Circle(2)]:
    print(type(shape).__name__, shape.area())   # same call, different behaviour

print(len("hello"), len([1, 2, 3]))             # built-in polymorphism
print(3 + 4, "3" + "4")

Output

Rectangle 12
Circle 12.57
5 3
7 34
  • The loop calls shape.area() without checking the type. Each class supplies its own area(), so the right formula runs.
  • The base class Shape raises NotImplementedError to signal that every subclass must provide area(). The abc module can enforce this more strictly.
  • Python’s built-ins are polymorphic too: len() works on strings and lists, and + adds numbers but joins strings.

Duck typing

Python does not require a shared parent class. Any object with an area() method would work in that loop. “If it walks like a duck and quacks like a duck, it is a duck.”

Encapsulation with Underscores and @property

class Thermostat:
    def __init__(self, celsius):
        self._celsius = celsius          # "protected" by convention
        self.__log = []                  # name-mangled ("private")

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -50 or value > 60:
            raise ValueError("out of range")
        self.__log.append(value)
        self._celsius = value

    def changes(self):
        return len(self.__log)

t = Thermostat(25)
t.celsius = 30                           # goes through the setter
print(t.celsius, t.changes())
try:
    t.celsius = 99
except ValueError as e:
    print("Rejected:", e)
print(hasattr(t, "__log"), hasattr(t, "_Thermostat__log"))

Output

30 1
Rejected: out of range
False True
  • _celsius (one underscore) means “internal, please do not touch”. Python does not block access; it is a convention.
  • __log (two underscores) triggers name mangling: Python renames it to _Thermostat__log, so it is hard to reach by accident from outside.
  • @property makes t.celsius look like a plain attribute but runs a method. The @celsius.setter method validates every assignment, which is why 99 was rejected.

The Four Pillars of OOP

PillarIdeaIn Python
EncapsulationBundle data with methods and guard itClasses, _name, @property
AbstractionExpose what an object does, hide howSimple public methods, abc.ABC
InheritanceReuse a parent’s codeclass Car(Vehicle)
PolymorphismOne interface, many formsOverriding, duck typing

Inheritance is covered in Python Inheritance.

Common Mistakes

  1. Thinking __name makes data truly private. It only renames it; determined code can still reach it.
  2. Naming the property and the stored attribute the same. Inside the setter, self.celsius = value calls the setter again forever. Store the value in self._celsius.
  3. Writing getters and setters for everything. Use plain attributes, and switch to @property only when you need checks.

Practice Exercises

Exercise 1. Add a Square class to the shapes example without changing the loop.

Show answer
class Square(Shape):
    def __init__(self, side):
        self.side = side
    def area(self):
        return self.side ** 2

Add Square(5) to the list and the loop prints Square 25.

Exercise 2. Make an age property that refuses negative numbers.

Show answer
class Person:
    def __init__(self, age):
        self.age = age          # uses the setter

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if value < 0:
            raise ValueError("age cannot be negative")
        self._age = value

Frequently Asked Questions

Does Python have private variables?

Not strictly. A single underscore marks a name as internal by convention, and a double underscore triggers name mangling. Neither makes the data impossible to reach.

What is method overloading in Python?

Python does not support several methods with the same name and different parameters. Use default arguments or *args to get the same effect.

Summary

  • Polymorphism: the same method call adapts to each object’s class.
  • Duck typing means any object with the right method works.
  • _name is internal by convention; __name is name-mangled.
  • @property adds validation without changing how the attribute is used.
Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *