Answer the question
In order to leave comments, you need to log in
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'))
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question