+ 1

Python, Data Hiding, Class Methods

#Here is the code from SoloLearn Module troubling me: 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) #Can you explain the meaning of data hiding here? Also I cant understand what does setter do here and code after setter method. My interpretation: 1. We create an instance called pizza of the class Pizza, with its toppings-attribute equal to the list of strings given by ["cheese", "tomato"]. 2. When we use the code print(pizza.pineapple_allowed), it goes to that property method, making it a read only attribute, and then returns to self thus returning to False. I cant understand after that. Please Help!. All efforts will be upvoted and appreciated.

9th Sep 2019, 2:15 PM
Harshit Garg
1 Odpowiedź
+ 1
Data hiding means certain properties/methods are not accessible from outside of the class definition. instead, you need to call getter/setter functions. this ensures you only access data/methods if you're supposed to, or are at least specifically aware that you shouldn't be accessing them like this. so what happens after the 2nd line is that the setter is called to set instance pizza's property pineapple_allowed to true, thus the following line should print true. however, the setter method calls for an input() and only sets the property if the input is equal to the password. if the password isn't entered correctly, it will raise a ValueError (exception) and output the string "Alert! Intruder!". @ syntax defines decorators, in this case for a getter and setter method. I hope that covers everything.
26th Dec 2019, 12:34 AM
grdr