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.
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.
_variable (Single Underscore): Indicates a protected variable. It should not be accessed directly, but Python doesn't strictly prevent you from doing so.__variable (Double Underscore): Indicates a private variable. Python performs "name mangling" to make it harder to access from outside the class.
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()
By convention, how do you denote an attribute as private in Python to invoke name mangling?