我怎样才能获得所有可用特殊方法的清单?

zjm*_*126 0 python django

例如,特殊方法(在Django中):

def __wrapper__
def __deepcopy__
def __mod__
def __cmp__
Run Code Online (Sandbox Code Playgroud)

Est*_*ber 8

要打印Python的保留字只需使用

>>> 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']
Run Code Online (Sandbox Code Playgroud)

要阅读Python特殊对象方法的说明,请阅读手册Dive into Python.

你可以使用的另一个片段是

>>> [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__']
Run Code Online (Sandbox Code Playgroud)

查看str该类的所有内置特殊方法.


Ale*_*lli 5

特殊方法名称的列表是在这里,但它不是魔术的名字一个详尽的-例如,方法__copy____deepcopy__提及相反,__all__变量是在这里,类属性,如__name__,__bases__等在这里,等.我不知道任何给定版本的语言中定义的所有此类名称的任何单一权威列表.

但是,如果你想检查任何一个给定的特殊名称,比如说__foo__,只需在Python文档的"快速搜索"框中搜索它(以上任何一个URL都可以!) - 这样你会发现它它是语言的正式部分,如果你没有找到它,你就会知道某些包或框架错误地使用它会违反语言的惯例.