selfboot / AnnotatedShadowSocks

Annotated shadowsocks(python version)
Other
3 stars 1 forks source link

Double Underscore used in python #8

Open selfboot opened 7 years ago

selfboot commented 7 years ago

As #7 says, single underscore is mainly used for convention. In python, we also see double underscore time and again. For example ,in lru_cache.py there are __setitem__, __getitem__, __delitem__ and so on.

Double underscore used in python can be divided into two situations: name mangling and magic method.

Name mangling

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. As the python documentation says:

Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

Take the following example:

>>> class Parent(object):
...     def _internal_use(self):
...         pass
...     def __method_name(self):
...         pass
... 
>>> dir(Parent())
['_Parent__method_name', ..., '_internal_use']

As expected, _internal_use doesn’t change but method_name is mangled to `_ClassNamemethod_name. Now, if you create a subclass of Parent, say Child, then you can’t easily override A‘s__method_name`:

>>> class Child(Parent):
...     def __method_name(self):
...         pass
... 
>>> dir(Child())
['_Parent__method_name', '_Child__method_name', ..., '_internal_use']

Name mangling is intended to give classes an easy way to define “private” instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private.

Magic method

These are special method names used by Python. As far as one’s concerned, this is just a convention, a way for the Python system to use names that won’t conflict with user-defined names. You then typically override these methods and define the desired behaviour for when Python calls them. For example, you often override the __init__ method when writing a class.

There is nothing to stop you from writing your own special-method-looking name (but, please don’t)

Ref: Underscores in Python