How to change default behaviour of a class?

Michael Hudson mwh21 at cam.ac.uk
Mon Aug 30 06:37:36 EDT 1999


"Gerhard W. Gruber" <g.gruber at xsoft.co.at> writes:

> How can I change what is printed when I use the statement "print class"?
> Usually this leads to an output like <class instance at 9aad60> but I
> rather want it to print variables contained in my class instead of the
> pointer adress.

Add a __repr__ method:

class C:
    def __init__(self):
        self.a = 1
    def __repr__(self):
        return "self.a = %s"%self.a

C() => "self.a = 1" appears on stdout.

HTH,
Michael




More information about the Python-list mailing list