Encapsulation in Python

Previous
Next

Encapsulation:

  • The concept of protecting object information.
  • By implementing Encapsulation rules, an object behaves like real world entity.

Rules:

  1. Class is public – Object is visible to other objects in communication.
  2. Variables are private – One object cannot access the information of other object directly.
  3. Communication between objects using get() and set() methods to share the information.
class Emp:
    def __init__(self,num,name,salary):
        self.__num = num
        self.__name = name
        self.__salary = salary
        return

    def getNum(self):
        return self.__num

    def getName(self):
        return self.__name

    def getSalary(self):
        return self.__salary

    def setNum(self,num):
        self.__num = num
        return

    def setName(self,name):
        self.__name = name
        return

    def setSalary(self,salary):
        self.__salary = salary
        return

class Access:
    def main():
        print("Enter Emp details :")
        num = int(input("Emp Num : "))
        name = input("Emp Name : ")
        salary = float(input("Emp Sal : "))
        obj = Emp(num, name, salary)
        print("Name :",obj.getName())
        return

Access.main()
Previous
Next

Add Comment

Courses Enquiry Form