Python and object-oriented principles: encapsulation

packaging variables into a single variable for later use
2025-11-05 09:09
// updated 2025-11-05 12:04

Encapsulation (along with inheritance and polymorphism) form one of the three fundamental concepts of object-oriented programming:

  • encapsulation entails a "packaging-up" of variables in a single class
    • we would refer to an object of a class while using these variables
    • any object not belonging to a class could not directly access those variables
class Person:
  def __init__(self, name, age, job):
    self.name = name
    self.age = age
    self.job = job

class Animal:
  def __init__(self, name, age):
    self.name = name
    self.age = age

fluffy = Animal("Fluffy", 10)
print(fluffy.job)

# Output:
# (An AttributeError since the 'Animal' object has no attirbute 'job')

So, in the example above, when we instantiate a new Animal object, we can readily access its name and age variables ... but it has no variable for a job, unlike a Person!

The class thus encapsulates whatever variables its object(s) will have...

newer (in textbook-python) ➡️
Python and object-oriented principles: inheritance 🐍