One of the vital highly effective options of Object-Oriented Programming (OOP) in Python is information safety ā and thatās precisely the place Entry Modifiers and Encapsulation are available in.
On this weblog, I discover:
š§© Public, Protected, and Non-public Variables
Perceive how Python handles variable entry, and why entry management is important when designing scalable and safe packages. Youāll study the distinction between:
- public variables ā open to all
- protected variables ā meant for use inside subclasses
- personal variables ā restricted to the category itself
class Individual:
def __init__(self,identify,age,gender):
self._name= identify ## protected variables
self._age=age ## protected variables
self.gender=gender ## public variables## we can't entry these variables from exterior the category however we will entry then from Derived class.
class Worker(Individual):
def __init__(self,identify,age,gender):
tremendous().__init__(identify,age,gender)
worker= Worker("Prabh",23,"Male")
print(worker._name)
š Getter and Setter Strategies
See tips on how to entry and replace personal variables safely utilizing particular strategies, avoiding the danger of breaking inside logic from exterior interference.
## Encapsulation with Getter n Setterclass Individual:
def __init__(self,identify,age):
self.__name=identify ## Non-public variable
self.__age=age ## Non-public variable
## Getter technique for identify
def get_name(self):
return self.__name
## Setter technique for identify
def set_name(self,identify):
self.__name= identify
## Getter technique for age
def get_age(self):
return self.__age
## Setter technique for age Its is use to alter the worth.
def set_age(self,age):
if age > 0:
self.__age = age
else:
print("Age can't be detrimental.")
particular person= Individual('Prabh',23)
## Entry and modify personal variables utilizing getter n setter technique
print(particular person.get_name())
print(particular person.get_age())
print(particular person.set_age(24))
print(particular person.get_age())
print(particular person.set_age(-4))
š”ļø Encapsulation in Motion
Youāll discover real-life Python examples like a Individual and Worker class to see how encapsulation protects class information, promotes modular code, and reinforces cleaner programming construction.
šØāš» Whether or not youāre simply beginning with OOP or wish to reinforce your core Python information, this publish will allow you to write cleaner, safer, and extra organized code.
š¬ Be at liberty to share your ideas or questions within the feedback ā letās study and develop collectively!
š #Python #ObjectOrientedProgramming #Encapsulation #AccessModifiers #PythonForBeginners #CleanCode #PythonOOP #SoftwareDesign #100DaysOfCode #DataScienceJourney