OOP Python – Encapsulation – Why Needed
class Hello:
def __init__(self):
self.normal_variable = 200
self.__private_variable = 900 #double underscore...private variable
obj = Hello()# object creation
print('Printing Normal Variable: ',obj.normal_variable)# will execute normally
print('Printing Private Variable: ',obj.__private_variable)# throw an error
Output: Printing Normal Variable: 200
print('Printing Private Variable: ',obj.__private_variable)
AttributeError: 'Hello' object has no attribute '__private_variable'
OOP Python – Encapsulation – How to Access
class Hello:
def __init__(self):
self.normal_variable = 200
self.__private_variable = 900 #double underscore...private variable
def use_private_variable(self):
print('Printing Private Variable from method: ',obj.__private_variable)
obj = Hello()# object creation
print('Printing Normal Variable: ',obj.normal_variable)
obj.use_private_variable()# using private variable with Encapsulation
Output: Printing Normal Variable: 200
Printing Private Variable from method: 900