- 1
what is s._Spam__egg do ??
class Spam: __egg = 7 def print_egg(self): print(self.__egg) s = Spam() s.print_egg() print(s._Spam__egg) print(s.__egg) what is s._Spam__egg do ?? how it works
1 Réponse
0
__egg is a variable that is created when you create a new instance of the class Spam, in this case 's'. If a variable has two underscores before it (__) then it is considered highly private and cannot be called by the standard method of for example s.egg.
So even though __egg is highly private, you can still (although not recommended) access that variable outside the class if you really need to. To do that you do a special method call with the instance of the class, the class name preceded by an underscore and then the private variable name. That is how you get
s._Spam__egg
which works when you try and print it out in the above statement, but printing s.__egg throws an error.