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
Accessor and Mutator Methods in Python
Accessor and mutator methods in Python are used to access and modify the private data of a class. In object-oriented programming, class data is encapsulated ? meaning the object data is kept private and cannot be directly accessed from outside the object. These methods provide controlled access to private variables and are also known as getter and setter methods.
Accessor Methods (Getters)
An accessor method is used to retrieve object data. Private variables of an object can be accessed through accessor methods, which are public methods that return private member data.
In Python, accessor methods are defined using the @property decorator. This allows you to access private variables like attributes while maintaining encapsulation ?
Example
class Person:
def __init__(self, name):
self.__name = name # Private variable
@property
def name(self):
return self.__name
# Create object and access private variable
person = Person("John")
print(person.name)
The output is ?
John
Mutator Methods (Setters)
A mutator method is used to modify an object's private data. These methods provide controlled access to change private variables, allowing validation or processing before assignment.
In Python, mutator methods are defined using the @<property_name>.setter decorator ?
Example
class Person:
def __init__(self, name):
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if isinstance(value, str) and value.strip():
self.__name = value
else:
raise ValueError("Name must be a non-empty string")
# Create object and modify private variable
person = Person("John")
person.name = "Jane"
print(person.name)
The output is ?
Jane
Complete Example with Validation
Here's a practical example showing both accessor and mutator methods with data validation ?
class BankAccount:
def __init__(self, balance):
self.__balance = balance
@property
def balance(self):
return self.__balance
@balance.setter
def balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("Balance cannot be negative")
# Usage
account = BankAccount(1000)
print(f"Initial balance: ${account.balance}")
account.balance = 1500
print(f"Updated balance: ${account.balance}")
account.balance = -100 # This will show error message
print(f"Final balance: ${account.balance}")
The output is ?
Initial balance: $1000 Updated balance: $1500 Balance cannot be negative Final balance: $1500
Conclusion
Accessor and mutator methods provide controlled access to private class variables in Python. Use @property for getters and @property_name.setter for setters. This approach maintains encapsulation while allowing validation and controlled data modification.
