pythonの動的追加オブジェクトメソッド


python3.1動的にメソッドを追加するには、まずImport typesが必要です
 
import types
class Demo:
    def hello(self):
        print("hello world")

helloInstance = Demo()
def hello2(self):
    print ("hello again")
Demo.hello2 =hello2         #     hello2  
helloInstance.hello()
helloInstance.hello2()

def hello3(self):
    print ("hello once more")
helloInstance2 = Demo()
helloInstance2.hello()
helloInstance2.hello2()
helloInstance2.hello3 =hello3   #        hello3  
helloInstance2.hello3(helloInstance2)

helloInstance4 = Demo()
helloInstance4.hello()
helloInstance4.hello2()
helloInstance4.hello3(helloInstance4)

 
 
実行結果は次のとおりです.
 
hello world hello again hello world hello again hello once more hello world hello again Traceback (most recent call last):   File "C:/Python31/hello2", line 24, in     helloInstance4.hello3(helloInstance4) AttributeError: 'Demo' object has no attribute 'hello3'
 
結果分析:このクラスにhello 2を定義すると、後で生成されたすべてのインスタンスがこのメソッドを呼び出すことができることが分かった.3番目のインスタンスに特化して定義されたhello 3メソッドは、4番目のインスタンスによって呼び出されません.ここからpython動的生成の強さがわかり、クラスまたは特定のインスタンスにメソッドを定義して使用できます.
 
Ps:python3.0の後、newはtypesに取って代わられた.だからimport newはImportError:No module named newエラーを報告します