Python property()
is a built-in function that returns a property attribute for classes.
property(fget=None, fset=None, fdel=None, doc=None)
Where,
The property()
function is used to provide methods to control the access of attributes. Using property()
function we can bind the getter, setter and deleter function altogether or individually with an attribute name.
To create a property, we define the instance variable and one or more method functions.
Now let’s see how property()
is used in Python with a program to convert currency (currency_y = currency_x * 28
).
class CurrencyConverter:
def __init__(self, currency_x = 1):
self.currency_x = currency_x
def currency_converter(self):
currency_y = self.get_currency_x() * 28
return (currency_y)
#implementing new getter method
def get_currency_x(self):
print ('inside getter method')
return (self._currency_x)
#implementing new setter method
def set_currency_x(self, currency_value):
if currency_value < 0:
raise ValueError("Currency can't be negative")
print ('inside setter method')
self._currency_x = currency_value
currency_x = property(get_currency_x, set_currency_x)
Now, let’s try to get, set and convert the value of the currency.
Output
>>> #Creating new object
>>> c = CurrencyConverter(2)
inside setter method
>>> #get the value of currency_x using getter method
>>> c.get_currency_x()
inside getter method
2
>>> #converting the currency
>>> c.currency_converter()
inside getter method
56
In above example, the property()
function attaches the defined getter and setter methods to the variable currency_x
. Now, whenever a value is assigned to currency_x
, set_currency_x()
method will be automatically invoked.