single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

1

Tkinter.Toplevel(master,class_='ClassName')

__double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo). 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. This invokes Python’s name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.

Note 1: Note that only the simple class name is used in the mangled name, so if a subclass chooses both the same class name and attribute name, you can still get name collisions.

Note 2: Name mangling can make certain uses, such as debugging and __getattr__() , less convenient. However the name mangling algorithm is well documented and easy to perform manually.

Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.

__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.

Note that names with double leading and trailing underscores are essentially reserved for Python itself: “Never invent such names; only use them as documented”.

Dunder functions

Another term of “dunder functions” is “magic methods”, they mean the ones with “__double_leading_and_trailing_underscore__”. here is a detail document about this topic.

Here are the rules you should follow for dunders:

Call them “dunders” — Terminology like “magic” makes them seem much more complicated than they actually are. For example, it’s the “dunder call method”, not the “double-underscore call double-underscore method” and not the “magic call method”.

Implement dunders on your classes at will — There is nothing magic about them, you shouldn’t feel like you’re using an esoteric language feature when you implement the __call__ method. Because, you’re not! It’s a standard language feature just like __init__!

Never, ever, invent your own dunders — Python leaves you with a number of clean namespaces (classes, modules, etc.) for your own code. Use them! The core Python team reserved a somewhat ugly namespace for themselves — don’t trample all over their compromise by stealing their names.

>>>classDummy(object):...def__init__(self,params):...self.params=params......def__getattr__(self,name):...iftype(self.params)isdict:...returnself.params.get(name)...else:...raiseValueError('params is not dict instance.')>>>d=Dummy({'a':1,'b':2,'add':lambdax,y:x+y})>>>d.a1>>>d.b2>>>d.add(1,2)3