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
@propertyadds 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 ownarea(), so the right formula runs. - The base class
ShaperaisesNotImplementedErrorto signal that every subclass must providearea(). Theabcmodule 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.@propertymakest.celsiuslook like a plain attribute but runs a method. The@celsius.settermethod validates every assignment, which is why 99 was rejected.
The Four Pillars of OOP
| Pillar | Idea | In Python |
|---|---|---|
| Encapsulation | Bundle data with methods and guard it | Classes, _name, @property |
| Abstraction | Expose what an object does, hide how | Simple public methods, abc.ABC |
| Inheritance | Reuse a parent’s code | class Car(Vehicle) |
| Polymorphism | One interface, many forms | Overriding, duck typing |
Inheritance is covered in Python Inheritance.
Common Mistakes
- Thinking
__namemakes data truly private. It only renames it; determined code can still reach it. - Naming the property and the stored attribute the same. Inside the setter,
self.celsius = valuecalls the setter again forever. Store the value inself._celsius. - Writing getters and setters for everything. Use plain attributes, and switch to
@propertyonly 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.
_nameis internal by convention;__nameis name-mangled.@propertyadds validation without changing how the attribute is used.
