Python provides a more elegant and convenient way to define getters and setters using the property
function.
This function allows you to define a property that is used like an attribute, but with the ability to control its access and modification.
Properties make access to attributes feel more natural, and their syntax is cleaner and easier to understand.
Defining Properties
The property
function is used to define a property. You can optionally pass a getter, a setter, and a deleter to this function.
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@name.setter
def name(self, name):
if isinstance(name, str):
self._name = name
else:
raise ValueError("Name must be a string")
@property
def age(self):
return self._age
@age.setter
def age(self, age):
if isinstance(age, int) and age > 0:
self._age = age
else:
raise ValueError("Age must be a positive integer")
Using Properties
With the properties defined, you can get and set values using attribute syntax, making the code cleaner and more readable.
For example,
person = Person("John", 25)
print(person.name) # Output: John
person.name = "Carlos"
print(person.name) # Output: Carlos
print(person.age) # Output: 25
person.age = 30
print(person.age) # Output: 30
Notice that I don’t have to invoke a setter or getter method. I simply get the value with .
, and set it with =
, just like it were an attribute.