python在运行时给class添加方法,pythonclass,下面的代码演示如何在运行


下面的代码演示如何在运行时给类添加__str__方法。通过这个例子也可以了解__dict__和__class__的用法

import stringimport newdef __str__(self):    classStr = ''    for name, value in self.__class__.__dict__.items( ) + self.__dict__.items( ):         classStr += string.ljust( name, 15 ) + '\t' + str( value ) + '\n'    return classStrdef addStr(anInstance):    anInstance.__str__ = new.instancemethod(__str__, anInstance, anInstance.__class__)# Test itclass TestClass:    classSig = 'My Sig'    def __init__(self, a = 1, b = 2, c = 3 ):        self.a = a        self.b = b        self.c = ctest = TestClass()addStr( test )print test

评论关闭