简体   繁体   中英

Calling methods surrounded by __ in Python

I'm reading a book on Python, and it says that when you make a call to help(obj) to list all of the methods that can be called on obj , the methods that are surrounded by __ on both sides are private helper methods that cannot be called.

However, one of the listed methods for a string is __len__ and you can verify that if s is some string, entering s.__len__() into Python returns the length of s .

Why is okay to call some of these methods, such as __len__ , but others cannot be called?

The book is incorrect. You can call __dunder__ special methods directly; all that is special about them is their documented use in Python and how the language itself uses them.

Most code just should not call them directly and leave it to Python to call them. Use the len() function rather than call the __len__ method on the object, for example.

The language reserves all such names for its own use; see Reserved classes of identifiers in the reference documentation:

System-defined 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM