Welcome, guest | Sign In | My Account | Store | Cart

This recipe demonstrates the runtime addition of a __str__ method to a class instance. This can sometimes be useful for debugging purposes. It also demonstrates the use of the two special attributes of class instances: '__dict__' and '__class__'.

Python, 24 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import string
import new

def __str__(self):
    classStr = ''
    for name, value in self.__class__.__dict__.items( ) + self.__dict__.items( ): 
        classStr += string.ljust( name, 15 ) + '\t' + str( value ) + '\n'
    return classStr

def addStr(anInstance):
    anInstance.__str__ = new.instancemethod(__str__, anInstance, anInstance.__class__)

# Test it

class TestClass:
    classSig = 'My Sig'
    def __init__(self, a = 1, b = 2, c = 3 ):
        self.a = a
        self.b = b
        self.c = c
    
test = TestClass()
addStr( test )
print test