[Python] Why doesn't a string object have an __int__ method for integer conversion?

Discussão em 'Python' iniciado por Stack, Maio 28, 2025.

  1. Stack

    Stack Membro Participativo

    My current understanding of Python's built-in functions and dunder or magic methods is that they are linked to each other. For example, if you create a list object and use the len-function the list object's dunder method __len__ is finally called.

    a = [1,2,3]
    len(a) # is equal to a.__len__()


    However, this seams different with a string object and integer conversion.

    a = "3"
    i = int(a) # --> don't call a.__int__()
    print(dir(a)) # --> __int__() event don't exist


    I always thought that the built-in functions only work if the equivalent dunder method exists. But that doesn't seem to be the case.

    Why and how does the conversion really work?

    Continue reading...

Compartilhe esta Página