Swashy
Swashy

Reputation: 187

How to display a class like a called variable?

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

Upvotes: 0

Views: 61

Answers (1)

alecxe
alecxe

Reputation: 473893

You should use __repr__():

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

Also see:

Hope that helps.

Upvotes: 4

Related Questions