문제

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