dspjm
dspjm

Reputation: 5860

How to print printable object info in python

See:

>>> class A:
...     a = 3
... 
>>> tmp=A()
>>> tmp
<__main__.A instance at 0xb7340c2c>
>>> A
<class __main__.A at 0xb733c26c>
>>> tmp.a
3

I want tmp.a also have the output like 'tmp' and 'A', is that possible?

Please notice this like tmp not in tmp. So what I want will be:

>>> tmp.a
<int tmp.a at ...>

Upvotes: 2

Views: 84

Answers (2)

oz123
oz123

Reputation: 28898

Each object can have a __str__ and you can also define a __repr__ method, which will be printed.

>>> class A(object):
...     a = 3
...     def __str__(self):
...         return repr(self)+': a: %d' % self.a
...     def __repr__(self):
...         return 'A object with id %d ' % id(self)
...
>>> b=A()
>>> b
A object with id 4340531472
>>> print b
A object with id 4340531472 : a: 3

Upvotes: 4

Jayanth Koushik
Jayanth Koushik

Reputation: 9904

No, tmp.a is an integer object. It will be displayed like any other integer object. You can however define use a function to get a representation for a.

class A:
    a = 3
    def repr_a(self):
        return repr(self) + ': a: ' + str(self.a)

The 'printable info' for any object is actually controlled by the __repr__ or __str__ function. So, you can simply define that.

class A:
    a = 3
    def __repr__(self):
        return 'Class A: a = ' + str(self.a)

Upvotes: 0

Related Questions