문서자료/Python

[Python] Recipe 52192: Add a method to a class instance at runtime

nineclouds 2009. 11. 26. 00: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

<<<결과내용>>>
__module__     __main__
__doc__         None
__init__       <function __init__ at 0x017F6170>
classSig       My Sig
a               1
c               3
b               2
__str__         <bound method TestClass.__str__ of <__main__.TestClass instance at 0x017F4260>>