Implementing Getters and Setters with Decorators
In Python, you can implement getters
and setters
more concisely using decorators
.
In programming, decorators are used to extend or modify the functionality of functions or methods. In Python, decorators are applied using the @
symbol.
The decorators used for defining getters and setters are as follows:
-
@property
: Defines a getter method. It allows you to access a method like an attribute. -
@attribute_name.setter
: Defines a setter method. It allows you to set or modify the attribute value.
class Person:
def __init__(self, name):
self.__name = name
@property # Define getter method
def name(self):
return self.__name
@name.setter # Define setter method
def name(self, value):
if isinstance(value, str):
self.__name = value
else:
raise ValueError("Name must be a string.")
person = Person("John")
# Use getter
print(person.name) # Output: 'John'
# Use setter
person.name = "Steve" # Change the name
print(person.name) # Output: 'Steve'
# Attempt to set invalid value (raises an error)
# person.name = 123
# # ValueError: Name must be a string.
In the code above, __name
is a private variable of the Person
class.
The @property
decorator defines the name
method as a getter, while the @name.setter
decorator defines the name
method as a setter.
Using decorators like this makes implementing getters and setters more concise.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.