How can i get a list of all special methods available?
Special methods are for example (in Django):
def __wrapper__
def __deepcopy__
def 开发者_运维知识库__mod__
def __cmp__
To print Python's reserved words just use
>>> import keyword
>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass',
'raise', 'return', 'try', 'while', 'with', 'yield']
To read an explanation of special object methods of Python, read the manual or Dive into Python.
Another snippet you can use is
>>> [method for method in dir(str) if method[:2]=='__']
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__',
'__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__']
to see all the built in special methods of the str
class.
A list of special method names is here, but it's not an exhaustive of magic names -- for example, methods __copy__
and __deepcopy__
are mentioned here instead, the __all__
variable is here, class attributes such as __name__
, __bases__
, etc are here, and so on. I don't know of any single authoritative list of all such names defined in any given release of the language.
However, if you want to check on any single given special name, say __foo__
, just search for it in the "Quick search" box of the Python docs (any of the above URLs will do!) -- this way you will find it if it's officially part of the language, and if you don't find it you'll know it is a mistaken usage on the part of some package or framework that's violating the language's conventions.
You can find most of them here: http://docs.python.org/genindex-all.html#_
identifiers with 2 leading+2 trailing underscores are of course reserved for special method names. Although it is possible to define such identifiers now, may not be the case in future. __deepcopy__, __mod__, and __cmp__ are all special methods built into python that user classes can override to implement class-specific functionality.
精彩评论