Why does python use two underscores for certain things?

前端 未结 7 1336
滥情空心
滥情空心 2020-11-27 15:43

I\'m fairly new to actual programming languages, and Python is my first one. I know my way around Linux a bit, enough to get a summer job with it (I\'m still in high school)

相关标签:
7条回答
  • 2020-11-27 16:25

    Here is the creator of Python explaining it:

    ... rather than devising a new syntax for special kinds of class methods (such as initializers and destructors), I decided that these features could be handled by simply requiring the user to implement methods with special names such as __init__, __del__, and so forth. This naming convention was taken from C where identifiers starting with underscores are reserved by the compiler and often have special meaning (e.g., macros such as __FILE__ in the C preprocessor).

    ...

    I also used this technique to allow user classes to redefine the behavior of Python's operators. As previously noted, Python is implemented in C and uses tables of function pointers to implement various capabilities of built-in objects (e.g., “get attribute”, “add” and “call”). To allow these capabilities to be defined in user-defined classes, I mapped the various function pointers to special method names such as __getattr__, __add__, and __call__. There is a direct correspondence between these names and the tables of function pointers one has to define when implementing new Python objects in C.

    0 讨论(0)
提交回复
热议问题