All courses › Intermediate Programming › Encapsulation and polymorphism

Encapsulation and polymorphism

Encapsulation means hiding internal state behind a controlled interface; in Python, internal attributes are often marked with a leading underscore, as in _value. Polymorphism means different classes can have a method with the same name but different behaviour.

_name\_\text{name}convention for an internal attribute
areaCircle≠areaRectangle\text{area}_{\text{Circle}} \neq \text{area}_{\text{Rectangle}}same method name, different implementation

Example

Sirkel.areal() and Rektangel.areal() both use the name areal, but compute it completely differently.

Polymorphism lets you call .areal() on a list of different shapes without checking the type first.
Practise object orientation for free →

← Inheritance and super() · @property →

Part of Intermediate Programming: Object orientation.