Python Polymorphism & EncapsulationGet Certified
What Is Polymorphism?
Polymorphism means “many forms.” In Python it lets objects of different classes respond to the same method name in their own way. You can write one piece of code that works with several kinds of objects, and each object supplies the correct behavior. A list of animals can all answer speak(), yet a dog barks and a cat meows. Polymorphism reduces if-else chains, makes programs easier to extend, and is one of the central ideas of object-oriented design. Python supports it both through inheritance and through a flexible style called duck typing.
- Same interface, different behavior: objects share a method name but implement it differently.
- Inheritance polymorphism: child classes override a parent method.
- Duck typing: “If it walks like a duck and quacks like a duck, it is a duck.” No shared parent is required.
- One call site: the calling code does not need to know the exact class of each object.
Polymorphism Through Method Overriding
The most common form of polymorphism uses inheritance. A parent class defines a method, and each child class supplies its own version. When you call the method on an object, Python looks up the version that belongs to that object’s class. The calling code stays simple: it treats every object the same way. This pattern is especially useful when you later add a new child class; existing loops and functions continue to work without change.
Try It: Animals That Speak Differently
Click Test My Code. Add a third child class named Bird that returns "Tweet" and include it in the list.
Animal class with a default speak() method. Dog and Cat override the method. A loop calls speak() on every animal without checking the exact type.class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
pets = [Dog(), Cat(), Animal()]
for pet in pets:
print(type(pet).__name__, pet.speak())Animal is the shared parent. It supplies a default sound.speak() returns three dots for any generic animal."...".Dog inherits from Animal."Woof".Cat also inherits from Animal."Meow".speak() for each object. The output shows three different results.Polymorphism With a Shared Interface
A useful design is to define a method in a base class that every child must implement, even if the base version only raises an error. The children then supply the real logic. Client code can call that method on any object from the family and trust that each object will respond correctly. This approach keeps the interface clear and makes the program easy to extend later with new shapes, payments, or other kinds of objects.
Try It: Shapes That Calculate Area
Click Test My Code. Change the radius of the circle to 5 and watch the printed area update.
Shape class promises an area() method. Rectangle and Circle each provide their own formula. A loop prints the area of every shape without caring which concrete class it is.class Shape:
def area(self):
raise NotImplementedError("Subclasses must implement area()")
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
shapes = [Rectangle(4, 6), Circle(3)]
for s in shapes:
print(type(s).__name__, round(s.area(), 2))Shape defines the common interface.area() must be implemented by every concrete shape.NotImplementedError makes the requirement clear.Rectangle inherits from Shape.Circle also inherits from Shape.area() for each object and the areas are printed.Duck Typing in Python
Python does not force you to share a common parent class. If two unrelated objects both implement a method with the same name and compatible behavior, you can use them interchangeably. This style is called duck typing. It keeps code flexible and is widely used in the standard library and in everyday scripts. The trade-off is that errors appear only when a missing method is actually called, so careful naming and testing remain important.
Try It: Objects That Can Be Drawn
Click Test My Code. Notice that Button and Picture share no parent, yet both work with the same function.
draw() method. A helper function accepts any object that has draw() and calls it. No inheritance is required.class Button:
def draw(self):
return "Drawing a button"
class Picture:
def draw(self):
return "Drawing a picture"
def render(item):
print(item.draw())
render(Button())
render(Picture())Button is a standalone class.draw() method.Picture is completely independent of Button.draw().render accepts any object that has a draw() method.draw() and prints the result.Button is passed. The output is Drawing a button.Picture is passed. The output is Drawing a picture.What Is Encapsulation?
Encapsulation means keeping an object’s internal data hidden and controlling how that data is read or changed. Instead of letting every part of a program reach inside an object and modify attributes directly, you provide a small set of public methods that are the only safe way to interact with the object. This protects the object from invalid values, makes future changes easier, and reduces accidental bugs. In Python the convention is to mark attributes that should not be used from outside with a single underscore, and name mangling with a double underscore gives stronger protection.
- Hide internal state: attributes that other code should not touch directly.
- Control access: methods or properties that validate and update the data.
- Single underscore: a convention that signals “for internal use.”
- Double underscore: triggers name mangling so the attribute is harder to reach from outside.
Name Mangling and Private Attributes
When you name an attribute with two leading underscores, Python rewrites the name so that it includes the class name. The rewritten name is still accessible if you know the mangled form, but everyday code outside the class will not find the original name. This is the strongest privacy mechanism Python offers without external libraries. It is commonly used for data that must stay consistent, such as a bank balance or an internal counter.
Try It: A Bank Account With a Private Balance
Click Test My Code. Try to print acct.__balance and observe the error, then use the public methods instead.
BankAccount class stores the balance under a double-underscore name. Deposits and withdrawals go through public methods that keep the balance non-negative. Direct access to the private attribute fails.class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return True
return False
def get_balance(self):
return self.__balance
acct = BankAccount("Jordan Lee", 500)
acct.deposit(150)
print(acct.owner, acct.get_balance())
print(acct.withdraw(100))
print(acct.get_balance())BankAccount models a simple checking account.if statement checks that the amount is greater than zero.Using Properties for Controlled Access
Python's @property decorator lets you write methods that look like ordinary attributes when they are used. You can validate values on assignment, compute a value on the fly, or keep a private attribute while still offering a clean public interface. Properties are the preferred modern way to implement getters and setters. They keep client code simple and still give the class full control over its data.
Try It: A Temperature That Rejects Invalid Values
Click Test My Code. Try assigning a negative temperature and read the error message that appears.
Temperature class stores Celsius in a private attribute. A property allows reading and writing the value while rejecting negative numbers. The client code uses ordinary attribute syntax.class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < 0:
raise ValueError("Temperature cannot be negative")
self._celsius = value
t = Temperature(22)
print(t.celsius)
t.celsius = 18
print(t.celsius)Temperature stores a temperature reading.@property decorator turns the method into a readable attribute.t.celsius calls this method.ValueError is raised if the value is invalid.Combining Polymorphism and Encapsulation
The two ideas work well together. A family of classes can share a public interface while each class keeps its own private data. Client code calls the same methods on every object and never needs to know about the internal details. This combination produces clean, maintainable designs that are easy to extend later with new subclasses.
Try It: Vehicles With Private Fuel Levels
Click Test My Code. Notice that both vehicles respond to drive() yet manage their fuel differently behind the scenes.
Vehicle class defines a public drive() method and keeps the fuel level private. Car and Truck override the distance calculation while still using the same public interface.class Vehicle:
def __init__(self, model, fuel):
self.model = model
self.__fuel = fuel
def drive(self, miles):
needed = self._fuel_needed(miles)
if needed <= self.__fuel:
self.__fuel -= needed
return f"{self.model} drove {miles} miles"
return f"{self.model} needs more fuel"
def _fuel_needed(self, miles):
return miles * 0.05
def get_fuel(self):
return self.__fuel
class Car(Vehicle):
def _fuel_needed(self, miles):
return miles * 0.04
class Truck(Vehicle):
def _fuel_needed(self, miles):
return miles * 0.08
fleet = [Car("Civic", 12), Truck("F-150", 20)]
for v in fleet:
print(v.drive(100))
print("Fuel left:", round(v.get_fuel(), 1))Vehicle holds the shared public interface and private fuel.Car inherits from Vehicle.Truck also inherits from Vehicle.Polymorphism in Practice With Collections
Once objects share a common interface, you can store them in lists, pass them to functions, and process them uniformly. This is one of the most practical benefits of polymorphism. A payroll system can loop over employees of different ranks, a drawing program can render a list of shapes, and a game can update every character with a single call. The code that uses the objects stays short and readable.
Try It: A Simple Payroll
Click Test My Code. Add a third employee of a new subclass and confirm the loop still works without any change.
Employee base class defines pay(). Salaried and Hourly employees override it. A list of mixed employees is processed with one loop.class Employee:
def __init__(self, name):
self.name = name
def pay(self):
return 0
class Salaried(Employee):
def __init__(self, name, monthly):
super().__init__(name)
self.monthly = monthly
def pay(self):
return self.monthly
class Hourly(Employee):
def __init__(self, name, rate, hours):
super().__init__(name)
self.rate = rate
self.hours = hours
def pay(self):
return self.rate * self.hours
staff = [
Salaried("Ava Thompson", 4200),
Hourly("Liam Carter", 22.5, 160)
]
for person in staff:
print(f"{person.name}: ${person.pay():,.2f}")Employee supplies the shared name and a default pay method.Salaried inherits from Employee.Hourly also inherits from Employee.pay() method for each object and formats the result with two decimal places.Encapsulation Best Practices
Good encapsulation keeps the public surface of a class small and stable. Prefer properties over bare attributes when validation or computation is needed. Use a single underscore for "internal" attributes that subclasses may still touch, and reserve double underscores for data that truly must stay private. Document the public methods clearly so that other programmers know the intended way to use the class. Avoid exposing implementation details that you may want to change later.
Common Mistakes With Polymorphism and Encapsulation
Most problems arise from treating private data as public, or from assuming that two classes share a method when they do not. The list below covers the mistakes that appear most often when students first combine these two ideas.
- Reaching into private attributes: writing
obj.__balancefails; use the public methods or properties instead. - Forgetting to override: a child class that does not supply its own version of a method will silently use the parent's (possibly incorrect) version.
- Inconsistent method signatures: if one subclass expects different arguments, client code that treats all objects the same will break.
- Using type checks instead of polymorphism: long chains of
if isinstance(...)defeat the purpose of a shared interface. - Making everything private: over-use of double underscores makes testing and subclassing harder than necessary.
- Changing a property's meaning: a property should continue to behave like the attribute it replaces so that existing code keeps working.
Key Takeaways
Polymorphism and encapsulation are complementary tools. Polymorphism lets you write code that works with many kinds of objects through a common interface. Encapsulation protects each object's data and gives you a controlled way to change that data. Together they produce programs that are easier to read, safer to change, and simpler to extend. The points below summarize the essentials you will use in almost every object-oriented design.
- Polymorphism means different classes can respond to the same method name in their own way.
- Method overriding and duck typing are the two main routes to polymorphism in Python.
- Encapsulation hides internal data and exposes a small, stable public interface.
- Use a single underscore for internal attributes and a double underscore for stronger name mangling.
- Prefer
@propertyfor controlled access that still looks like ordinary attribute syntax. - Combine both ideas: public methods that hide private state, and subclasses that override those methods.
- Store related objects in collections and process them uniformly through the shared interface.
Frequently Asked Questions
The questions below are the ones that students ask most often when they first meet polymorphism and encapsulation. Each answer is short and practical, and each idea appears in one of the examples above. Experiment with the live code boxes to confirm the behavior for yourself.
What is polymorphism in Python?
Polymorphism is the ability of different classes to respond to the same method name with their own behavior. You can call the method on any object that supports it, and Python selects the correct implementation at runtime.
What is the difference between polymorphism and inheritance?
Inheritance is a way to share code and form an "is-a" relationship. Polymorphism is the ability to treat different objects through a common interface. Inheritance is one common way to achieve polymorphism, but duck typing achieves it without a shared parent class.
What is duck typing?
Duck typing means that Python cares about the methods an object provides, not about its exact class or inheritance tree. If an object has a method named draw, any function that calls draw can use that object.
What does encapsulation mean in Python?
Encapsulation means keeping an object's internal data hidden and controlling how that data is read or changed. Public methods and properties form the only intended way for outside code to interact with the object.
What is the difference between a single underscore and a double underscore?
A single leading underscore is a convention that signals "this is for internal use." A double leading underscore triggers name mangling, which rewrites the attribute name so that it is harder to reach from outside the class.
When should I use a property instead of a plain attribute?
Use a property when you need to validate a value, compute it on the fly, or keep a private attribute while still offering a clean public interface. The client code continues to use ordinary attribute syntax.
Can I combine polymorphism and encapsulation?
Yes. A base class can define public methods that operate on private data, and subclasses can override those methods while still protecting their own internal state. Client code then works with the public interface only.
Why is polymorphism useful with lists and loops?
When objects share a method name, you can store them in a single list and process every item with the same call. New subclasses can be added later without changing the loop that uses them.