猿问
回到首页
个人中心
反馈问题
注册登录
下载APP
首页
课程
实战
体系课
手记
专栏
慕课教程
向现有对象实例添加方法
向现有对象实例添加方法
我已经读到,可以在Python中向现有对象(即类定义中)添加一个方法。
我知道这样做并不总是好的。但如何才能做到这一点呢?
哆啦的时光机
浏览 402
回答 3
3回答
白衣非少年
在Python中,函数和绑定方法是有区别的。>>> def foo():... print "foo"...>>> class A:... def bar( self ):... print "bar"...>>> a = A()>>> foo<function foo at 0x00A98D70>>>> a.bar<bound method A.bar of <__main__.A instance at 0x00A9BC88>>>>>绑定方法已被“绑定”(如何描述性)到实例,每当调用该方法时,该实例将作为第一个参数传递。不过,作为类的属性(相对于实例)的可调用对象仍未绑定,因此您可以随时修改类定义:>>> def fooFighters( self ):... print "fooFighters"...>>> A.fooFighters = fooFighters>>> a2 = A()>>> a2.fooFighters<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>>>> a2.fooFighters()fooFighters以前定义的实例也会被更新(只要它们没有重写属性本身):>>> a.fooFighters()fooFighters当您想要将方法附加到单个实例时,问题就出现了:>>> def barFighters( self ):... print "barFighters"...>>> a.barFighters = barFighters>>> a.barFighters()Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: barFighters() takes exactly 1 argument (0 given)当函数直接附加到实例时,它不会自动绑定:>>> a.barFighters<function barFighters at 0x00A98EF0>要绑定它,我们可以使用类型模块中的方法类型函数:>>> import types>>> a.barFighters = types.MethodType( barFighters, a ) >>> a.barFighters<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88 >>>>> a.barFighters()barFighters这一次,该类的其他实例没有受到影响:>>> a2.barFighters()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: A instance has no attribute 'barFighters'更多信息可通过阅读描述符和元类 编程.
0
0
0
打开App,查看更多内容
随时随地看视频
慕课网APP
相关分类
Python
继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续