gpt4 book ai didi

python - 向现有对象实例添加方法

转载 作者:IT老高 更新时间:2023-10-28 12:01:04 25 4
gpt4 key购买 nike

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

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

最佳答案

在 Python 中,函数和绑定(bind)方法是有区别的。

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

已绑定(bind)的方法已“绑定(bind)”(如何描述)到一个实例,并且该实例将作为第一个参数在方法被调用时传递。

不过,作为类属性(而不是实例)的可调用对象仍然是未绑定(bind)的,因此您可以随时修改类定义:

>>> 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)

该函数在直接附加到实例时不会自动绑定(bind):

>>> a.barFighters
<function barFighters at 0x00A98EF0>

要绑定(bind)它,我们可以使用 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

这次该类的其他实例没有受到影响:

>>> a2.barFighters()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'barFighters'

更多信息可以通过阅读 descriptors 找到。和 metaclass programming .

关于python - 向现有对象实例添加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com