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 <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错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值