0

I see some strange but useful double underscored attribute in Python, such as:

__module__
__init__
__str__
__class__
__repr__
...

They seem to be some special attributes. What's the canonical name for them?

smwikipedia
  • 61,609
  • 92
  • 309
  • 482

2 Answers2

5

They are called Special Methods.

Python is a Duck Typed Language and many of the user-facing features of the language are implemented in "protocols" implemented by these special methods.

See: http://docs.python.org/release/2.5.2/ref/specialnames.html

As an Example:

To mimic comparison of arbitrary objects you implement the following two methods in your class:

  • __lt__
  • __eq__
James Mills
  • 18,669
  • 3
  • 49
  • 62
2

Per "Naming conventions" section of PEP-8

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

vartec
  • 131,205
  • 36
  • 218
  • 244