What is a “setter”/“getter”?
A “setter” is the method on a class that “sets” a property. Similarly a “getter” “gets” the property. Typically these are called something likemake = car.get_make() and car.set_make('VW'). In other languages you, as the user, can’t simply edit a class property like you can in Python, so these make a lot more sense. However, what you can do in Python is use the @property decorator.
How to use @property
Let’s consider the HatchBack example from Part 1, but this time we will call make make_stored and create a method called make with the 'property decorator applied to it that returns the make_stored property.
'Skoda' but if we know try to set the make property, by running car.make = 'VW', we can’t!
property decorator effectively turns a method into a ‘getter’ and blocks the user from setting the property (unless a setter is defined, which we’ll get to). A common pattern is to make the property on the class itself private and make the @property the same but public, which hides the “real” property and makes it look like it can’t be changed. Pretty neat!
getter. For example, if your class needs to fetch a lot of data from a server to calculate the value a property takes, you can put that fetching code in the getter. That way, the data is loaded only on demand, i.e. it is only fetched and loaded when the method is called and NOT when the class is instantiated. When you’re creating a lot of instances of a class that each contain a lot of data this can be very beneficial.
How to make a setter?
You could just leave it there; perhaps your property doesn’t need to be affected by the user. However, if it does then you need to build a setter. This requires a new decorator. This one will be the name of your getter method, dot, “setter”, e.g.@make.setter. It must also have a parameter besides self for whatever is being set to it. I always call it value.