python动态创建对象_python动态给对象或者类添加方法

In Python, there is a difference between functions and bound methods.

>>>deffoo():...print"foo"...>>>classA:...defbar(self):...print"bar"...>>>a=A()>>>foo>>>a.bar>>>>

Bound methods have been "bound" (how descriptive) to an instance, and that instance will be passed as the first argument whenever the method is called.

Callables that are attributes of a class (as opposed to an instance) are still unbound, though, so you can modify the class definition whenever you want:

>>>deffooFighters(self):...print"fooFighters"...>>>A.fooFighters=fooFighters>>>a2=A()>>>a2.fooFighters>>>>a2.fooFighters()fooFighters

Previously defined instances are updated as well (as long as they haven't overridden the attribute themselves):

>>>a.fooFighters()fooFighters

The problem comes when you want to attach a method to a single instance:

>>>defbarFighters(self):...print"barFighters"...>>>a.barFighters=barFighters>>>a.barFighters()Traceback(most recent call last):File"",line1,inTypeError:barFighters()takes exactly1argument(0given)

The function is not automatically bound when it's attached directly to an instance:

>>>a.barFighters

>>>importtypes>>>a.barFighters=types.MethodType(barFighters,a)>>>a.barFighters>>>>a.barFighters()barFighters

This time other instances of the class have not been affected:

>>>a2.barFighters()Traceback(most recent call last):File"",line1,inAttributeError:A instance has no attribute'barFighters'

More information can be found by reading about descriptors and metaclass programming.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值