Python: Generic getters and setters

前端 未结 5 461
天命终不由人
天命终不由人 2021-02-04 06:11

TL;DR: Having to define a unique set of getters and setters for each property()\'d variable sucks. Can I define generic getters and setters and use them with whatever

5条回答
  •  一向
    一向 (楼主)
    2021-02-04 06:42

    A colleague of mine suggested using closures to return getter and setter functions, which is what I've decided to use.

    class Foo(object):
        def setter(var):
            def set(self, value):
                setattr(self, var, value+' unicorn')
            return set
    
        def getter(var):
            def get(self):
                return getattr(self, var)+' sasquatch'
            return get
    
        bar = property(getter('_bar'), setter('_bar'))
    
    f = Foo()
    f.foo = 'hi'
    print f.foo
    

    But thank you all for your answers :)

提交回复
热议问题