我试图使用另一个更通用的类方法定义一些类方法,如下所示:
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)
工作正常。
您正在函数上创建部分,而不是方法。
functools.partial()
对象不是描述符,它们本身不会添加self
参数,并且不能自己充当方法。您可以只包装绑定的方法或函数,它们根本不适用于未绑定的方法。这是documented:请改用
property
s;这些是描述符:从Python 3.4开始,您可以在这里使用新的^{} object ;当绑定到实例时,它会做正确的事情:
但是必须调用它们,而
property
对象可以用作简单的属性。相关问题 更多 >
编程相关推荐