0

I am in the process of learning python. Specifically, it is about the get and set methods in the class. Question that popped up in my head is: What is the difference (apart from the call itself) between the @property and @ var.setter decorator and the regular setter. Example:

class Car:
    def __init__(self, mark):
        self.mark = mark
        self.__year = None

    def get_year(self):
        return self.__year

    def set_year(self, y):
        if y<2000:
            self.__year = "Old"
        else:
            self.__year = "New"

audi = Car("Audi")
audi.set_year(2005)
print(audi.get_year())

vs

class Car:
    def __init__(self, mark):
        self.mark = mark
        self.__year = None

    @property
    def year(self):
        return self.__year

    @year.setter
    def year(self, y):
        if y<2000:
            self.__year = "Old"
        else:
            self.__year = "New"

audi = Car("Audi")
audi.year = 2005
print(audi.year)

the only difference is calling? Is there anything else in it?

Thank you for explain

AnnAc0nda
  • 38
  • 6

1 Answers1

1

Yes, the main difference is the way that the values are accessed. Having a setter with the property allows for validation like in the example you provided.

EDIT: Another benefit of properties is that it allows you to turn existing class variables into properties without having to modify code that uses these variables

See this link for more information about the property decorator.

Chris
  • 108
  • 7
  • Thank you for answer!As far as i know a solution using the methods alone also allows you to validate the variables – AnnAc0nda Oct 01 '22 at 22:24
  • @AnnAc0nda that's true - the `@property` also allows you to turn existing normal class variables into properties with getters/setters without changing existing code that uses those variables – Chris Oct 01 '22 at 22:25