向现有对象实例添加方法

向现有对象实例添加方法

我已经读到,可以在Python中向现有对象(即类定义中)添加一个方法。

我知道这样做并不总是好的。但如何才能做到这一点呢?


哆啦的时光机
浏览 402回答 3
3回答

白衣非少年

在Python中,函数和绑定方法是有区别的。>>> def foo():...&nbsp; &nbsp; &nbsp;print "foo"...>>> class A:...&nbsp; &nbsp; &nbsp;def bar( self ):...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print "bar"...>>> a = A()>>> foo<function foo at 0x00A98D70>>>> a.bar<bound method A.bar of <__main__.A instance at 0x00A9BC88>>>>>绑定方法已被“绑定”(如何描述性)到实例,每当调用该方法时,该实例将作为第一个参数传递。不过,作为类的属性(相对于实例)的可调用对象仍未绑定,因此您可以随时修改类定义:>>> def fooFighters( self ):...&nbsp; &nbsp; &nbsp;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 ):...&nbsp; &nbsp; &nbsp;print "barFighters"...>>> a.barFighters = barFighters>>> a.barFighters()Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>TypeError: barFighters() takes exactly 1 argument (0 given)当函数直接附加到实例时,它不会自动绑定:>>> a.barFighters<function barFighters at 0x00A98EF0>要绑定它,我们可以使用类型模块中的方法类型函数:>>>&nbsp;import&nbsp;types>>>&nbsp;a.barFighters&nbsp;=&nbsp;types.MethodType(&nbsp;barFighters,&nbsp;a&nbsp;) >>>&nbsp;a.barFighters<bound&nbsp;method&nbsp;?.barFighters&nbsp;of&nbsp;<__main__.A&nbsp;instance&nbsp;at&nbsp;0x00A9BC88 >>>>>&nbsp;a.barFighters()barFighters这一次,该类的其他实例没有受到影响:>>>&nbsp;a2.barFighters()Traceback&nbsp;(most&nbsp;recent&nbsp;call&nbsp;last): &nbsp;&nbsp;File&nbsp;"<stdin>",&nbsp;line&nbsp;1,&nbsp;in&nbsp;<module>AttributeError:&nbsp;A&nbsp;instance&nbsp;has&nbsp;no&nbsp;attribute&nbsp;'barFighters'更多信息可通过阅读描述符和元类&nbsp;编程.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python