[Python] Default method to return a value for Python class [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    Is there a default method that can be called automatically that returns a value, but retains the type of the value? In a way, similar to how __str__ is called when you pass the class to say the print function.

    class Example:
    def __init__(value):
    self.value = value


    Now, I can create the following:

    e1 = Example(15)
    e2 = Example(200.145)
    e3 = Example("Some string")


    such that if I do:

    • int1 = e1 (int1 will have the value 15)
    • float1 = e2 (float1 should have the value 200.145)
    • string1 = e3 (string1 should have the value "Some string")

    I tried with __repr__ but that did not work.

    Is this possible?

    Continue reading...

Compartilhe esta Página