Python类变量将函数更改为方法,为什么



为什么Python在赋值给类变量时将自由函数转换为未绑定的方法?

def make_func(s):
    def func(x):
        return '%s-%d' % (s, x)
    return func
class Foo(object):
    foofunc = make_func('foo')

所以这按预期工作:(返回"dog-1"(

make_func('dog')(1)

但这失败了:

Foo.foofunc(1)

TypeError: unbound method func() must be called with Foo instance as first argument (got int instance instead)

经过仔细检查,Python 将 make_func 内部func的"inner"函数变成了一个方法,但由于没有self,这种方法将永远不起作用。为什么 Python 会这样做?

>>> import inspect
>>> inspect.getmembers(Foo, inspect.ismethod)
[('foofunc', <unbound method Foo.func>)]

Python 无法判断你"如何"将方法分配给类属性。 这两者之间没有区别:

class Foo(object):
    def meth():
        pass

而这个

def func():
    pass
class Foo(object):
    meth = func

在这两种情况下,结果都是将函数对象分配给名为 'meth' 的类属性。 Python 无法判断您是通过在类中定义函数来分配它,还是通过使用 meth = func "手动"分配它。 它只能看到"最终结果",这是一个值为函数的属性。 无论哪种方式,一旦函数在类中,它就会通过常规过程转换为方法,该过程会注意到类定义中的函数并将它们转换为方法。

class Foo(object):
    foofunc = make_func('foo')

foofunc是一个类变量,而不是一个方法(你需要'def'(。然后你用 make_func(...( 的结果初始化它,这样它就不会再次更改。

如果要调用 Foo.foofunc,则需要分配不带参数的foofunc = make_func

最新更新