向现有对象实例添加方法 [英] Adding a Method to an Existing Object Instance
问题描述
我已经阅读到可以在Python中向现有对象添加方法(即,不在类定义中).
I've read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python.
我知道这样做并不总是一件好事.但是怎么可能呢?
I understand that it's not always good to do so. But how might one do this?
推荐答案
在Python中,函数和绑定方法之间存在差异.
In Python, there is a difference between functions and bound methods.
>>> 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>>
>>>
绑定方法已绑定"(描述性强)到一个实例,并且无论何时调用该方法,该实例都将作为第一个参数传递.
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:
>>> 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
先前定义的实例也会被更新(只要它们本身没有覆盖属性):
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:
>>> 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)
该函数直接附加到实例时不会自动绑定:
The function is not automatically bound when it's attached directly to an instance:
>>> a.barFighters
<function barFighters at 0x00A98EF0>
要绑定它,我们可以在 MethodType函数中使用类型模块:
To bind it, we can use the MethodType function in the types module:
>>> import types
>>> a.barFighters = types.MethodType( barFighters, a )
>>> a.barFighters
<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>>
>>> a.barFighters()
barFighters
这一次该类的其他实例未受影响:
This time other instances of the class have not been affected:
>>> a2.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'barFighters'
More information can be found by reading about descriptors and metaclass programming.
这篇关于向现有对象实例添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!