【发布时间】:2013-05-13 16:03:52
【问题描述】:
我正在尝试使用另一个更通用的类方法来定义一些类方法,如下所示:
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) 有效。
【问题讨论】:
-
这是一个有用的问题,我不想偏离重点,但作为您代码的一个附带问题,我想知道您为什么要编写 super(RGB, self)。 __init__(),什么时候RGB继承自object?
-
@CaptainLepton 这是一个很好的做法,以防有一天有人添加了一个超类。
-
@michaelb958--GoFundMonica 你的意思是把
RGB超类变成一个新的书面子类?
标签: python exception methods functools