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__'.
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
|
Tags: debugging
There is a Better Way to Add Methods To Classes. This method creates a cycle in the object for no reason at all. The following function will add any function to an instance in a cycle free way:
Use as follows:
def pretty_str(self): pass
add_method(C(), pretty_str, '__str__') Moshe Zadka
@Moshe: Doesn't your recipe assumes that no attributes have been set on the object earlier ? Anyway, your recipe suits my purpose. Thanks.
Caveat in above code: Directly setting the method on the class will affect other instances of class.
Time to make this recipe PEP8 compliant, wouldn't you say?
Changelog: Changed camelCase and spacing to PEP8 compliant naming conventions.