When I’m using the get and set function to encapsulate the data from the user, property function was the solution to handle it.
I got the right solution with this code:
class Car:
def __init__(self, model, year, price):
self.__model = model
self.year = year
self.price = price
def setmodel(self, model):
self.__model = model
def getmodel(self):
return self.__model
model = property(getmodel, setmodel)
number_of_wheels = 4
car1 = Car("BMW", 2000, 10000)
car1.model = "AAA"
print(car1.model)
In other case where I put
model = property(setmodel, getmodel) – setmodel before the getmodel – I got this error:
TypeError: getmodel() takes 1 positional argument but 2 were given
I still can’t get it why the order here give an error?
>Solution :
model = property(setmodel, getmodel)
The reason why this gives you an error is because the first param is a get and the 2nd param is the set.
property(fget, fset, fdel, doc)
fget: (Optional) Function for getting the attribute value. Default value is none.
fset: (Optional) Function for setting the attribute value. Default value is none.
fdel: (Optional) Function for deleting the attribute value. Default value is none.
doc: (Optional) A string that contains the documentation. Default value is none.
SOURCE:https://www.tutorialsteacher.com/python/property-function
Documentation from Python: https://docs.python.org/3/library/functions.html#property