本文介绍了functools.partial 类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用另一个更通用的类方法来定义一些类方法,如下所示:

I'm trying to define some class methods using another more generic class method as follows:

class RGB(object):
    def __init__(self, red, blue, green):
        super(RGB, self).__init__()
        self._red = red
        self._blue = blue
        self._green = green

    def _color(self, type):
        return getattr(self, type)

    red = functools.partial(_color, type='_red')
    blue = functools.partial(_color, type='_blue')
    green = functools.partial(_color, type='_green')

但是当我尝试调用任何这些方法时,我得到:

But when i attempt to invoke any of those methods i get:

rgb = RGB(100, 192, 240)
print rgb.red()
TypeError: _color() takes exactly 2 arguments (1 given)

我猜 self 没有传递给 _color 因为 rgb.red(rgb) 有效.

I guess self is not passed to _color since rgb.red(rgb) works.

推荐答案

您是在 函数 上创建部分,而不是方法.functools.partial() 对象不是描述符,它们本身不会添加 self 参数,也不能作为方法本身.您可以包装绑定的方法或函数,它们根本不适用于未绑定的方法.这是记录:

You are creating partials on the function, not the method. functools.partial() objects are not descriptors, they will not themselves add the self argument and cannot act as methods themselves. You can only wrap bound methods or functions, they don't work at all with unbound methods. This is documented:

partial 对象类似于 function 对象,因为它们是可调用的、弱可引用的,并且可以具有属性.有一些重要的区别.例如,__name____doc__ 属性不会自动创建.此外,在类中定义的 partial 对象的行为类似于静态方法,并且不会在实例属性查找期间转换为绑定方法.

使用 property 代替;这些描述符:

Use propertys instead; these are descriptors:

class RGB(object):
    def __init__(self, red, blue, green):
        super(RGB, self).__init__()
        self._red = red
        self._blue = blue
        self._green = green

    def _color(self, type):
        return getattr(self, type)

    @property
    def red(self): return self._color('_red')
    @property
    def blue(self): return self._color('_blue')
    @property
    def green(self): return self._color('_green')

从 Python 3.4 开始,您可以使用新的 functools.partialmethod() 对象 在这里;当绑定到一个实例时它会做正确的事情:

As of Python 3.4, you can use the new functools.partialmethod() object here; it'll do the right thing when bound to an instance:

class RGB(object):
    def __init__(self, red, blue, green):
        super(RGB, self).__init__()
        self._red = red
        self._blue = blue
        self._green = green

    def _color(self, type):
        return getattr(self, type)

    red = functools.partialmethod(_color, type='_red')
    blue = functools.partialmethod(_color, type='_blue')
    green = functools.partialmethod(_color, type='_green')

但是这些必须被调用,而 property 对象可以用作简单的属性.

but these'd have to be called, whilst the property objects can be used as simple attributes.

这篇关于functools.partial 类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 09:08