+ 3

Better hide it from the kids - about name-mangling

In Python there is no real privacy; you write a single underline in front of a name so that a programmer using the class knows: 'I'm not supposed to touch this.' Double underscores at the beginning on the other side actually do something: They change the way you can access this value. This is supposed to prevent name clashes between base classes and inheriting classes. This is really vague in my head. I can see that we should prevent name clashes, but I can't imagine how they would occur in this case. Do you guys know a few easy real life examples where and how that __ would do its job, how to actually apply it with meaning?

2nd Jan 2019, 9:14 AM
HonFu
HonFu - avatar
1 Réponse
+ 3
These references might help you: 1. _single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore. 2.single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g. Tkinter.Toplevel(master, class_='ClassName') 3.__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below). 4. __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented. Read more at: https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
2nd Jan 2019, 11:58 AM
Iftekhar alam
Iftekhar alam - avatar