在 Python 中调用被 __ 包围的方法
Calling methods surrounded by __ in Python
我正在读一本关于 Python 的书,它说当你调用 help(obj)
列出所有可以在 obj
上调用的方法时,两边被__
包围的方法是不能调用的私有辅助方法
但是,列出的字符串方法之一是 __len__
,您可以验证 s
是否是某个字符串,将 s.__len__()
输入 Python returns s
.
的长度
为什么这些方法有的可以调用,比如__len__
,有的却不能调用?
这本书不正确。可以直接调用__dunder__
个特殊方法;它们的所有特殊之处在于它们在 Python 中的使用记录以及语言本身如何使用它们。
大多数代码不应该直接调用它们,而是让 Python 去调用它们。使用 len()
函数而不是调用对象上的 __len__
方法,例如,因为 len()
will validate the __len__
return value.
该语言保留所有此类名称供自己使用;请参阅参考文档中的 Reserved classes of identifiers:
System-defined names, informally known as "dunder" names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__
names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.
我正在读一本关于 Python 的书,它说当你调用 help(obj)
列出所有可以在 obj
上调用的方法时,两边被__
包围的方法是不能调用的私有辅助方法
但是,列出的字符串方法之一是 __len__
,您可以验证 s
是否是某个字符串,将 s.__len__()
输入 Python returns s
.
为什么这些方法有的可以调用,比如__len__
,有的却不能调用?
这本书不正确。可以直接调用__dunder__
个特殊方法;它们的所有特殊之处在于它们在 Python 中的使用记录以及语言本身如何使用它们。
大多数代码不应该直接调用它们,而是让 Python 去调用它们。使用 len()
函数而不是调用对象上的 __len__
方法,例如,因为 len()
will validate the __len__
return value.
该语言保留所有此类名称供自己使用;请参阅参考文档中的 Reserved classes of identifiers:
System-defined names, informally known as "dunder" names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of
__*__
names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.