Python: Generic getters and setters

前端 未结 5 462
天命终不由人
天命终不由人 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:58

    How about just:

    def sasquatchicorn(name):
        return property(lambda self: getattr(self, name) + ' sasquatch',
                        lambda self, val: setattr(self, name, val + ' unicorns'))
    
    class Foo(object):
        bar = sasquatchicorn('_bar')
        baz = sasquatchicorn('_baz')
    

    Somewhat more generically:

    def sasquatchify(val):
        return val + ' sasquatch'
    
    def unicornify(val):
        return val + ' unicorns'
    
    def getset(name, getting, setting):
        return property(lambda self: getting(getattr(self, name)),
                        lambda self, val: setattr(self, name, setting(val)))
    
    class Foo(object):
        bar = getset('_bar', sasquatchify, unicornify)
        baz = getset('_baz', sasquatchify, unicornify)
    

    Or, with barely more work, you can use the full descriptor protocol, as described in agf's answer.

提交回复
热议问题