Encapsulation
Encapsulation is the process of making groups of objects. Encapsulation means binding variables and methods under single entity. In encapsulation code and data are wrapped together within a single unit.
A class is an example of encapsulation as it encapsulates all the data that is member functions, variables etc.
When a python class is created it contains the methods and the variable. Since it is the code in the methods that operates on the variable, in a properly encapsulated python class, method should define how member variables can be used. But that's where the things differ a bit in python from a language like java where we have "Access Modifier" like public, private , protected. In python there are no explicit access modifier and everything written with in the class(methods and variables) are public by default.
for example in the class Person there are two variables as you can see those variables are accessed through a method as well as directly.
Example
class Person :
def __init__(self, name,age=0): # Constructor of the class
self.name=name
self.age=age
def display(self): # Method definition
print(self.name)
print(self.age)
per=Person("technicalguptaji",27) # Object creation
per.display() # Accessing using class method
print(per.name)
# Accessing directly from outside
print(per.age)
Output
technicalguptaji
27
technicalguptaji
27
No comments:
Post a Comment