Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Property Function in Python

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading