Python Tutorial

Python Encapsulation Explained With Examples

Understanding Encapsulation in Python

You can use Python OOPS for restricting access to methods and variables. This is known as encapsulation, because it protects data from direct change. In Python, we use the underscore as a prefix to designate private characteristics, such as single or double.

  • Data Encapsulation in Python

class Computer:

    def __init__(self):

        self.__maxprice = 900

    def sell(self):

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

    def setMaxPrice(self, price):

        self.__maxprice = price

c = Computer()

c.sell()

# change the price

c.__maxprice = 1000

c.sell()

# using setter function

c.setMaxPrice(1000)

c.sell()

Output:

Selling Price: 900
Selling Price: 900
Selling Price: 1000

Video : https://youtu.be/3V90qEND-1o

Vidoe : https://youtu.be/Tufla8KMz9k

Did you find this article helpful?