Domanda

Say I declare:

x = 5

In a terminal if I type x, I get its value displayed.

5

I'd like to do this for a class object as well, which I imagine would be something like this?

class foo():
    def __init__(self)
        self.x = "derp"
    def __info__(self)
        return(self.x)  #Or print(self.x)??? I don't know.

It's simple, but possibly too simple for anyone to have needed it. I've searched all around about magic methods (an apparently still poorly documented feature), but the best I've found is str, repr, and call.

Does anyone know of such an elusive method? Thanks!!

Edit: durrr, its repr after all....

È stato utile?

Soluzione

You should use __repr__():

>>> class Foo():
...     def __repr__(self):
...         return "I'm Foo"
... 
>>> foo = Foo()
>>> foo
I'm Foo

Also see:

Hope that helps.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top