Python中奇怪的双重下划线属性(__attribute__)是什么?

smw*_*dia 0 python

我在Python中看到了一些奇怪但有用的双重下划线属性,例如:

__module__
__init__
__str__
__class__
__repr__
...
Run Code Online (Sandbox Code Playgroud)

它们似乎是一些特殊的属性.他们的规范名称是什么?

Jam*_*lls 5

它们被称为特殊方法.

Python是一种Duck类型语言,该语言的许多面向用户的功能都是通过这些特殊方法实现的"协议"实现的.

请参阅:http://docs.python.org/release/2.5.2/ref/specialnames.html

作为一个例子:

要模仿任意对象的比较,请在类中实现以下两种方法:

  • __lt__
  • __eq__