The @property decorator is a built-in decorator in Python that allows a method to be accessed as an attribute instead of as a method. When this decorator is applied to a method, it makes the method act like a read-only property of an object.
The purpose of @property is to provide a more elegant way of accessing and setting object properties without changing the interface of the class. By using the @property decorator, a method that would normally be called as a method, such as obj.get_property(), can be accessed like an attribute, such as obj.property.
Here is an example of using the @property decorator:
class Person: def __init__(self, first_name, last_name): self._first_name = first_name self._last_name = last_name @property def full_name(self): return f"{self._first_name} {self._last_name}" person = Person("John", "Doe") print(person.full_name) # output: John Doe
In the above example, full_name is a read-only property of the Person class, which concatenates the first name and last name of the person. The @property decorator is used to make the full_name method act like a read-only property, allowing it to be accessed like an attribute of the person object.
0 Comments