部分工具函数在类方法上

2024-05-11 13:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

我想self不会传递给_color,因为rgb.red(rgb)工作正常。


Tags: 方法self定义initdeftypegreenblue
1条回答
网友
1楼 · 发布于 2024-05-11 13:25:49

您正在函数上创建部分,而不是方法。functools.partial()对象不是描述符,它们本身不会添加self参数,并且不能自己充当方法。您可以包装绑定的方法或函数,它们根本不适用于未绑定的方法。这是documented

partial objects are like function objects in that they are callable, weak referencable, and can have attributes. There are some important differences. For instance, the __name__ and __doc__ attributes are not created automatically. Also, partial objects defined in classes behave like static methods and do not transform into bound methods during instance attribute look-up.

请改用propertys;这些描述符:

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开始,您可以在这里使用新的^{} object;当绑定到实例时,它会做正确的事情:

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对象可以用作简单的属性。

相关问题 更多 >