为了账号安全,请及时绑定邮箱和手机立即绑定

向现有对象实例添加方法

向现有对象实例添加方法

哆啦的时光机 2019-06-01 16:01:49
向现有对象实例添加方法我已经读到,可以在Python中向现有对象(即类定义中)添加一个方法。我知道这样做并不总是好的。但如何才能做到这一点呢?
查看完整描述

3 回答

?
白衣非少年

TA贡献1155条经验 获得超0个赞


在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'

更多信息可通过阅读描述符元类 编程.


查看完整回答
反对 回复 2019-06-01
  • 3 回答
  • 0 关注
  • 401 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信