Property allows to define getter and setters for attributes, which are called implicitly when the attribute is accessed or modified (without requiring a function call from the user/client)
By using property, attributes of a class can be modified while being backward compatible
Consider following class being implemented to store user data
Consider the use-case when the last_name of a person is changed
Since, in the above example, full_name is only set initially, it does not get changed when user changes last_name
To mitigate this, full_name can be changed into a function which returns the full name based on first_name and last_name
But this can break code which uses the initial class since code using full_name
attribute now have to call full_name()
method
Anyone depending on it can be told "this is the way things are now", or @property
decorator can be used to allow backward compatibility
@property
decorator A method can be converted to a property by adding a @property
decorator before the methodβs definition
This makes the method seem & function like an attribute
Output
This enables the method full_name()
to be accessible as attribute full_name
property()
method In Python, property()
is a built-in function that creates and returns a property object
The syntax of this function is
where, fget
is the function to get value of the attribute, fset
to set value, fdel
to delete the attribute and doc
is a string (like a comment)
These function arguments are optional, and can be set later by the methods, getter()
, setter()
, and deleter()
to specify fget
, fset
and fdel
Functions setter() and deleter() can also be assigned as decorator
Since the above example doesn't user setter method, attempting to set full_name
raises AttributeError
@<property-name>.setter
decorator can be used to assign setter for a property, where <property-name>
is the name of property (full_name
above)
Output
@<property-name>.deleter
decorator can be used to assign deleter method for a property
Output