python - Pythonic alternative to dict-style setter? -
people tend consider getters , setters un-pythonic, prefering use @property
instead. i'm trying extend functionality of class uses @property
support dict:
class oldmyclass(object): @property def foo(self): return self._foo @foo.setter def foo(self, value): self.side_effect(value) self._foo = value class newmyclass(object): @property def foo(self, key): # invalid python return self._foo[key] @foo.setter def foo(self, key, value): # invalid python self.side_effect(key, value) self._foo[key] = value
of course, create helper classes deal this, seems writing setter/getter functions take key , value simpler. there more pythonic way refactor?
what describe not case properties. properties allowing obj
(or rather, class) customize behavior of obj.prop = value
. if want customize obj.prop[key] = value
, need handle not in obj
in obj.prop
, means need make obj.prop
custom class. want here create custom class __setitem__
.
class foo(object): def __init__(self): self._vals = {} def __setitem__(self, key, val): do_side_effect(key, val) self._vals[key] = val
then in myclass's __init__
, self.foo = foo()
.
if want dict-like object know parent object (e.g., because side effect should take place on parent, pass parent argument foo:
class foo(object): def __init__(self, parent): self.parent = parent self._vals = {} def __setitem__(self, key, val): parent.do_side_effect(key, val) self._vals[key] = val
and in myclass.__init__
self.foo = foo(self)
.
with regard getters/setters, you're doing not typical getter/setter. kind of thing discouraged things getsomeprop()
, setsomeprop(value)
, there separate method each property get/set. in example, you're describing different, generalized get/set mechanism setting key-value pairs (which presumably have meaning object's behavior). having method setpair(key, value)
not worse having method called dosomething(arg1, arg2)
. here have parameter, task doesn't fit simple pattern of obj.key = value
. have layer of indirection if want key/value inobj.prop[key] = value
"know about" obj
; in assignment obj.prop[key] = value
, key , value 1 step removed obj
, interact directly prop
.
you simple method john smith optional suggests. whether want way or custom object described depends on how want api set up. there can readability benefits having code built around custom "data-holding" classes 1 outlined here, make implementation bit more complex.
Comments
Post a Comment