DEV Community

Encapsulation in Python

encapsulation is a method of wrapping data and functions into a single entity.Acts as a protective layer which means internal representation of an object is generally hidden from outside of the object's definition.

class Employee:
    def __init__(self,name,salary):
        #private
        self.name  = name
        #private member
        # not  accessible outside of  a class
        self.__salary  = salary

    def show(self):
        print("Name is", self.name, "and salary is", self.__salary)


emp = Employee("Jessa",  10000)
emp.show()    

# access salary from outside  of a class

print(emp.__salary)
Enter fullscreen mode Exit fullscreen mode

output

Name is Jessa and salary is 10000
AttributeError: 'Employee' object has no attribute '__salary'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)