質問

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....

役に立ちましたか?

解決

You should use __repr__():

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

Also see:

Hope that helps.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top