W
W
weranda2016-04-26 10:51:32
Python
weranda, 2016-04-26 10:51:32

What's the difference between string methods in Python with and without double underscore?

Greetings
In Python, a beginner and a dissonance arises in my head: I open the official Python 3 documentation line by line - some methods are described. I open PyCharm's help line help (help(str)) and see a different picture - in addition, there are many other methods written through a double underscore of the method name.
To illustrate, let's take two simple examples:

a = '012345'

print(len(a))
print(a.__len__())


print(a + '-678')
print(a.__add__('-678'))

The visible result of the work of determining the length of the string and adding the string are the same. What is the difference? Clarify please. I tried to find in the official documentation a description and a description of the differences between these record options, but in vain.
PS
In addition, I would like to know the difference in the output of help information in the terminal and in the Pycharm program. The terminal displays short help on lines, literally three methods, and Pycharm displays extensive help. Why is this and is it possible to display full help in the terminal?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-04-26
@weranda

When talking about special methods, keep in mind that they are meant to be called by the interpreter, not by you. You don't write my_object.__len__() but len(my_object), and if my_object is an instance of a user-defined class, then Python will call the __len__ instance method you implemented. However, for built-in classes like list, str, bytearray, and so on, the interpreter does it easier: CPython's implementation of len() returns the value of the ob_size field of a PyVarObject C structure, which represents any built-in object in memory. This is much faster than calling a method.
Typically, a special method is called implicitly. For example, the sentence
for i in x: implies a call to the iter(x) function, which, in turn, can
call the x.__iter__ ( ) method, if it is implemented.

Luciano Ramalho "Fluent Python"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question