'___int___ method missing from Built in Class in Python

When I call int("1"), I get 1. But when I call "1".__int__() I get an error. I checked the methods of the class str, and there really is no method __int__. This confuses me, because then I do not understand how int("1") is able to return anything at all! It shouldn't work either, but it does. How can you explain this?



Solution 1:[1]

Similarly it does not have a __float__ or __decimal__ or any other dedicated method for every single way to initialize an integer. This design would not make sense as it is neither extendable nor scalable.

And why would a string type care about converting a string to anything else? that is the "target"'s type/class problem to handle.

Instead, the int type/class's initializer knows how to handle different, relevant types.

I believe your confusion stems from the custom class's datamodel, by which one should implement __int__ in order to support passing an instance to int(...).

This makes sense because there is no way for Python's built-in types to "re-write" themselves when a custom class is defined.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1