Skip to main content
 首页 » 编程设计

python之在 Python 中调用被 __ 包围的方法

2025年05月04日11lexus

我正在读一本关于 Python 的书,它说当你调用 help(obj) 时列出可以在 obj 上调用的所有方法, 被 __ 包围的方法两边都是不能调用的私有(private)辅助方法。

但是,列出的字符串方法之一是 __len__你可以验证如果 s是一些字符串,输入 s.__len__()进入 Python 返回 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.