Encapsulation: ============== what is Encapsulation? ======================= 1) Core concept of OOP. 2) Basic Idea of encapsulation is: The wrapping up/Bundling of data members and methods of the class into the single unit. 3) Encapsulation in Python also ensures that objects are self-sufficient functioning pieces and can work independently. Why do we need Encapsulation? ============================= 1) Provide well-defined and reusable code 2) Prevents the accidental modifications or deletion. 3) Provides the security 4) reusability Access modifiers: ================ are use to restrict or provide the limited access to certain variables/data and/or methods while programming. ==> three types of access modifiers: 1) Public Members 2) Private members 3) Protected Members Note: Like java, there are no keyword (public, private and protected) in python. Encapsulation with Public members: ================================== Public members can be accessed anywhere within the class or from any part of the program. Note: all the class members are "public" type as default. # Encapsulation with Public access members class publicModifiers: def __init__(self,name,age): # name and age ==> local to the constructor # convert the local members to instance variables self.name = name self.age = age def Age(self): # accessing public modifier data print("Age of the person is = ",self.age) def call(self): self.Age() pmo = publicModifiers("Ravi",31) # accessing of public access data from outside the class but within the program print("The Name of the person is = ",pmo.name) pmo.Age() pmo.call() ================================================ Encapsulation with Private members: =================================== private members ==> __ the name of the data should be prefixed with '__' ==> are called as "private members". ex: __a, __p etc. # Encapsulation with Private members class Rectangle: # private members __length = 0 __breadth = 0 __area = 0 def __init__(self): self.__length = 7 self.__breadth = 9 # Printing of privarte data in the constructor print("The Length = ",self.__length) print("The Breadth = ",self.__breadth) def Area(self): self.__area = self.__length * self.__breadth print("The Area = ",self.__area) rect = Rectangle() # accessing private data from outside the class # print("The Length = ",rect.__length) # print("The Breadth = ",rect.__breadth) rect.Area() ============================================== Encapsulation with Protected Members: ===================================== protected members ==> _ ex: _a, _b etc. # ENCAPSULATIOON WITH PROTECTED MEMBERS class details: # protected members _name = "Kumar" _age = 28 _job = "Developer" class modification(details): def __init__(self): print("Name = ",self._name) print("Age = ",self._age) print("Designation = ",self._job) obj = modification() obj1 = details print("Name = ",obj1.name) print("Age = ",obj1.age) print("Designation = ",obj1.job)