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 <module>
helloInstance4.hello3(helloInstance4)
AttributeError: 'Demo' object has no attribute 'hello3'
结果分析:可以发现,为该类定义了hello2后,所有后面生成的实例都能调用该方法;而专为第三个实例定义的hello3方法,则不能被第四个实例调用。从这里可以看到python动态生成的强大,可以为类 或者一个具体实例定义一个方法并使用。
Ps:python3.0之后,new被types取代了。所以 import new将会报 ImportError: No module named new错误