Python Encapsulation

Python Encapsulation

Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data (attributes) and the methods that work on data within one unit.

This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data.


Private Variables in Python

In Python, we don't have the strict private, protected, and public keywords like in C++ or Java. However, we have a convention: we denote private attributes using underscore prefixes.

Encapsulation Example

class Computer:
  def __init__(self):
    self.__maxprice = 900 // Private attribute

def sell(self): print("Selling Price: {}".format(self.__maxprice))

def setMaxPrice(self, price): self.__maxprice = price

c = Computer() c.sell()

// Try to change the price directly (Will NOT work) c.__maxprice = 1000 c.sell()

// Use the setter function (Will work) c.setMaxPrice(1000) c.sell()


Exercise

?

By convention, how do you denote an attribute as private in Python to invoke name mangling?