I am having hard time understanding this. Let's say we have a snippet of code as such
class Animal:
def __init__(self, name, food):
self.name = name
self.__food = food
def getFood(self):
return self.__food
Then we initialize it
>>> animal = {}
>>> animal["dog"] = Animal("rusty", "delicious thing you never know")
Now, while accessing the attributes, It seems to not let me access __food
>>> animal["dog"].name
'rusty'
>>> animal["dog"].__food
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Animal instance has no attribute '__food'
Why does that fail. As we can clearly see I am using self.__food = food where __ is magic method. So how do I print the __food Magic attribute ?
__foodoutside the class body, then don't use leading underscores (the primary purpose of leading underscores is to weakly "hide" variables through name-mangling). You'll find it as_Animal__food_Animala magic method too?self.__food, you shouldn't even bother defininggetFood; just let the user accessself.fooddirectly.__init__and__add__—with double underscores on both sides, not just the left—which are there for your class to conform to a "protocol" used by Python or the stdlib.