Lecture

Implementing Getters and Setters with Decorators

In Python, decorators offer a more concise way to implement getters and setters compared to traditional methods.

Decorators are used in programming to extend or alter the behavior of functions and methods.

The decorators used for defining getters and setters are as follows:

  1. @property: Defines a getter method. It allows you to access a method like an attribute.

  2. @attribute_name.setter: Defines a setter method. It allows you to set or modify the attribute value.

Example of Getters and Setters Using Decorators
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.

This approach provides a cleaner and more Pythonic way to implement attribute access control.

Quiz
0 / 1

The @property decorator defines a setter method.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result