gpt4 book ai didi

python - 通过类属性调用的函数对象失败

转载 作者:太空狗 更新时间:2023-10-29 21:20:38 24 4
gpt4 key购买 nike

我目前有一个类系统,可以注册回调,然后在满足特定条件时调用它们。但是我在存储函数对象时遇到了一些问题。

答:

class Foo(object):
_callback = None

@classmethod
def Register(cls, fn):
cls._callback = fn

def Bar():
print "Called"

Foo.Register(Bar)
Foo._callback()

input clear Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux

Traceback (most recent call last): File "python", line 12, in <module>
TypeError: unbound method Bar() must be called with Foo instance as first argument (got nothing instead)

我不确定为什么当函数不是 Foo 的成员时它需要一个 Foo 实例。

乙:

class Foo(object):
_callback = []

@classmethod
def Register(cls, fn):
cls._callback.append(fn)

def Bar():
print "Called"

Foo.Register(Bar)
Foo._callback[0]()

为什么第一个版本不行而第二个版本可以?将其添加到列表时有什么功能不同。

最佳答案

每当您将一个函数分配给一个类对象时,它就变成了一个方法:

In [6]: Foo.baz = lambda self: 'baz'

In [7]: f = Foo()

In [8]: f.baz()
Out[8]: 'baz'

请注意,这意味着您可以动态地向类添加方法,这些方法将在实例化对象上可见!

In [9]: Foo.anothermethod = lambda self, x: x*2

In [10]: f.anothermethod(4)
Out[10]: 8

来自docs :

If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When an instance attribute is referenced that isn’t a data attribute, its class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.

关于python - 通过类属性调用的函数对象失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44443350/

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