Python: multiple properties, one setter/getter

bandana picture bandana · Jan 23, 2010 · Viewed 10.1k times · Source

Consider the following class definitions

class of2010(object):
    def __init__(self):
        self._a = 1
        self._b = 2
        self._c = 3

    def set_a(self,value):
        print('setting a...')
        self._a = value
    def set_b(self,value):
        print('setting b...')
        self._b = value
    def set_c(self,value):
        print('setting c...')
        self._c = value
    a = property(fset=self.set_a)
    b = property(fset=self.set_b)
    c = property(fset=self.set_c)

note that set_[a|b|c]() do the same thing. is there a way do define:

def set_magic(self,value):
    print('setting <???>...')
    self._??? = value

once and use it for a,b,c as follows

a = property(fset=self.set_magic)
b = property(fset=self.set_magic)
c = property(fset=self.set_magic)

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Jan 23, 2010
def attrsetter(attr):
  def set_any(self, value):
    setattr(self, attr, value)
  return set_any

a = property(fset=attrsetter('_a'))
b = property(fset=attrsetter('_b'))
c = property(fset=attrsetter('_c'))