我正在尝试使用另一个更通用的类方法来定义一些类方法,如下所示:
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)可以工作。
发布于 2013-05-19 00:57:23
你是在函数上创建偏导函数,而不是在方法上。functools.partial()对象不是描述符,它们本身不会添加self参数,也不能充当方法本身。您只能包装绑定的方法或函数,它们根本不适用于未绑定的方法。这是documented
partial对象类似于function对象,因为它们是可调用的、弱引用的,并且可以具有属性。这里有一些重要的区别。例如,__name__和__doc__属性不是自动创建的。此外,在类中定义的partial对象的行为类似于静态方法,并且在实例属性查找期间不会转换为绑定方法。
请改用property;这些是描述符:
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')从Python3.4开始,您可以在这里使用新的functools.partialmethod() 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对象可以用作简单的属性。
发布于 2020-03-12 09:57:03
partialmethod的问题是它不兼容inspect.signature,functools.wraps,...
奇怪的是,如果您自己使用partial documentation implementation example重新实现functools.partial,它将会工作:
# Implementation from:
# https://docs.python.org/3/library/functools.html#functools.partial
def partial(func, /, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = {**keywords, **fkeywords}
return func(*args, *fargs, **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfuncclass 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 = partial(_color, type='_red')
blue = partial(_color, type='_blue')
green = partial(_color, type='_green')
rgb = RGB(100, 192, 240)
print(rgb.red()) # Print red这是因为newfunc是一个用newfunc.__get__实现descriptor protocol的真函数。而type(functools.partial)是一个覆盖了__call__的自定义类。类不会自动添加self参数。
https://stackoverflow.com/questions/16626789
复制相似问题