Python Getters and Setters
In Python, getters and setters are used to control access to attributes of a class. They help in encapsulation by hiding the internal representation of an object and controlling how values are read or modified.
Python में getters और setters का उपयोग class के attributes तक सुरक्षित पहुंच बनाने के लिए किया जाता है। यह encapsulation में मदद करता है जिससे हम values को control कर सकते हैं।
Why Use Getters and Setters?
- To validate or control values before assigning.
- To protect direct access to private variables.
- To update internal logic without changing interface.
- Value assign करने से पहले उसे validate या control करने के लिए।
- Private variables को directly access करने से बचाने के लिए।
- Internal logic बदलने पर interface को change किए बिना update करने के लिए।
Example 1: Getter using @property
class Employee:
def __init__(self, name, salary):
self.name = name
self._salary = salary # protected attribute
@property
def salary(self):
return self._salary
e1 = Employee("Aryan", 50000)
print(e1.salary)
Output:
50000
Example 2: Setter using @property.setter
class Employee:
def __init__(self, name, salary):
self.name = name
self._salary = salary
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, value):
if value < 0:
print("Invalid salary")
else:
self._salary = value
e1 = Employee("Naincy", 60000)
e1.salary = 65000
print(e1.salary)
Output:
65000
Example 3: Validation inside setter
class Employee:
def __init__(self, name, salary):
self.name = name
self._salary = salary
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, value):
if not isinstance(value, (int, float)):
raise ValueError("Salary must be numeric")
if value < 0:
raise ValueError("Salary cannot be negative")
self._salary = value
e1 = Employee("Jay", 70000)
e1.salary = 80000
print(e1.salary)
Output:
80000