python - functools.partial on class method -
i'm trying define class methods using more generic class method 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 attempt invoke of methods get:
rgb = rgb(100, 192, 240) print rgb.red() typeerror: _color() takes 2 arguments (1 given)
i guess self not passed _color
since rgb.red(rgb)
works.
you creating partials on function, not method. functools.partial()
objects not descriptors, not add self
argument , cannot act methods themselves. can only wrap bound methods or functions, don't work @ unbound methods. documented:
partial
objectsfunction
objects in callable, weak referencable, , can have attributes. there important differences. instance,__name__
,__doc__
attributes not created automatically. also,partial
objects defined in classes behave static methods , not transform bound methods during instance attribute look-up.
use property
s 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')
as of python 3.4, can use new functools.partialmethod()
object here; it'll right thing when bound 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')
but these'd have called, whilst property
objects can used simple attributes.
Comments
Post a Comment