Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are Getters/Setters methods for Python Class?
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This restricts accessing variables and methods directly and can prevent the accidental modification of data.
In Python, getters and setters are methods used to access and modify private attributes of a class. These methods are a key part of encapsulation and help control how to access and update the data, especially when we want to protect the internal state of an object.
What are Getter Methods?
In Python, getter methods are used to access the values of class attributes. When variables are declared as private (using underscore conventions), getter methods allow us to access them from outside the class in a controlled manner.
The basic syntax for a getter method is ?
def get_attribute_name(self):
return self._attribute_name
What are Setter Methods?
In Python, setter methods are used to modify and update the value of a class attribute. They provide controlled access to change private variables with validation if needed.
The basic syntax for a setter method is ?
def set_attribute_name(self, value):
self._attribute_name = value
Basic Implementation of Getters and Setters
Here's a simple example showing how to implement getters and setters ?
class Student:
def __init__(self, name, age):
self._name = name
self._age = age
# Getter for name
def get_name(self):
return self._name
# Setter for name
def set_name(self, name):
self._name = name
# Getter for age
def get_age(self):
return self._age
# Setter for age with validation
def set_age(self, age):
if age > 0:
self._age = age
else:
print("Age must be positive")
# Create object
student = Student("Alice", 20)
# Using getters
print("Name:", student.get_name())
print("Age:", student.get_age())
# Using setters
student.set_name("Bob")
student.set_age(25)
print("Updated Name:", student.get_name())
print("Updated Age:", student.get_age())
Name: Alice Age: 20 Updated Name: Bob Updated Age: 25
Using property() Function
Python's property() function provides a more elegant way to create getters and setters. It allows you to access methods like attributes.
The syntax is ?
property(getter_method, setter_method, deleter_method)
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
# Getter method
def get_celsius(self):
return self._celsius
# Setter method
def set_celsius(self, value):
if value >= -273.15:
self._celsius = value
else:
print("Temperature cannot be below absolute zero")
# Create property
celsius = property(get_celsius, set_celsius)
# Create object
temp = Temperature(25)
# Access like an attribute
print("Temperature:", temp.celsius)
# Set like an attribute
temp.celsius = 30
print("Updated temperature:", temp.celsius)
# Try invalid temperature
temp.celsius = -300
Temperature: 25 Updated temperature: 30 Temperature cannot be below absolute zero
Using @property Decorator
The most Pythonic way to create getters and setters is using the @property decorator ?
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
"""Getter method"""
return self._radius
@radius.setter
def radius(self, value):
"""Setter method"""
if value > 0:
self._radius = value
else:
print("Radius must be positive")
@property
def area(self):
"""Calculated property"""
return 3.14159 * self._radius ** 2
# Create object
circle = Circle(5)
# Access properties
print("Radius:", circle.radius)
print("Area:", circle.area)
# Modify radius
circle.radius = 10
print("New radius:", circle.radius)
print("New area:", circle.area)
Radius: 5 Area: 78.53975 New radius: 10 New area: 314.159
Accessing Private Variables
In Python, truly private variables use double underscores (__). These variables undergo name mangling and can only be accessed through getter methods ?
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
# Getter for private variable
def get_balance(self):
return self.__balance
# Setter with validation
def set_balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Balance cannot be negative")
# Create account
account = BankAccount(1000)
# Access private variable through getter
print("Balance:", account.get_balance())
# Update balance
account.set_balance(1500)
print("Updated balance:", account.get_balance())
# Try to access private variable directly (this will cause AttributeError)
try:
print(account.__balance)
except AttributeError as e:
print("Error:", e)
Balance: 1000 Updated balance: 1500 Error: 'BankAccount' object has no attribute '__balance'
Benefits of Using Getters and Setters
| Benefit | Description | Example Use Case |
|---|---|---|
| Data Validation | Check values before setting | Age must be positive |
| Computed Properties | Calculate values on access | Area from radius |
| Encapsulation | Hide internal implementation | Private variables |
| Debugging | Track access and modifications | Log property changes |
Conclusion
Getters and setters provide controlled access to class attributes, enabling data validation and encapsulation. Use the @property decorator for the most Pythonic approach, as it allows attribute-like access while maintaining method functionality.
