Is there a term for functions starting and ending with the double underscore (init or getattr for example)? I understand their purpose, just wondering if there is a good way to refer to them! Thanks!
The use of double underscore ( __ ) in front of a name (specifically a method name) is not a convention; it has a specific meaning to the interpreter. Python mangles these names and it is used to avoid name clashes with names defined by subclasses.
A double underscore prefix causes the Python interpreter to rewrite the attribute name in order to avoid naming conflicts in subclasses. This is also called name mangling—the interpreter changes the name of the variable in a way that makes it harder to create collisions when the class is extended later.
Double underscores are used for fully private variables. According to Python documentation − If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores.
Underscore (_) in PythonSingle Underscore: Single Underscore in Interpreter. Single Underscore after a name. Single Underscore before a name. Single underscore in numeric literals.
I always heard them named "dunder functions" as a shortname for "double-underscore functions".
It's a name a bit surprising at first, but easy to say and understand when talking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With