+ 1

Python, Encapsulation / Data Hiding.

#Sharing a code from Sololearn's Module: class Pizza: def __init__(self, toppings): self.toppings = toppings self._pineapple_allowed = False @property def pineapple_allowed(self): return self._pineapple_allowed @pineapple_allowed.setter def pineapple_allowed(self, value): if value: password = input("Enter the password: ") if password == "Sw0rdf1sh!": self._pineapple_allowed = value else: raise ValueError("Alert! Intruder!") pizza = Pizza(["cheese", "tomato"]) print(pizza.pineapple_allowed) pizza.pineapple_allowed = True print(pizza.pineapple_allowed) #I am unable to understand the role of setter method here! My interpretation: The last 4th line of code creates an instance. The last third line refers to the pineapple_allowed(self) method which returns the False statement because of __init__. I am unable to understand the rest please help. Sorry if the question is lengthy! Thanks in Advance.

3rd Sep 2019, 7:32 PM
Harshit Garg
1 Antwort
+ 1
This lesson is not about classmethod, but Encapsulation / Data Hiding. The Pizza class has an instance variable _pineapple_allowed. Notice the underscore in the beginning that means it is a private variable that is not supposed to be changed directly from the outside. This is where python introduces the @property decorator. You have two functions with the same name (pineapple_allowed). The first one is the "getter" method whose purpose is to retrieve the hidden variable. The second function decorated by @pineapple_allowed.setter changes the hidden variable. Getter and setter functions (=properties) can be useful if you want to perform additional calculation or validation on the internal variables.
3rd Sep 2019, 8:04 PM
Tibor Santa
Tibor Santa - avatar