Python: Generic getters and setters

前端 未结 5 513
天命终不由人
天命终不由人 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条回答
  •  旧时难觅i
    2021-02-04 06:48

    This is what the descriptor protocol property is based on is for:

    class Sasicorn(object):                              
        def __init__(self, attr):                        
            self.attr = "_" + attr                       
        def __get__(self, obj, objtype):                 
            return getattr(obj, self.attr) + ' sasquatch'
        def __set__(self, obj, value):                   
            setattr(obj, self.attr, value + ' unicorns') 
    
    class Foo(object):                                   
        def __init__(self, value = "bar"):               
            self.bar = value                             
            self.baz = "baz"                             
        bar = Sasicorn('bar')                            
        baz = Sasicorn('baz')                            
    
    foo = Foo()                                          
    foo2 = Foo('other')                                  
    print foo.bar                                        
    # prints bar unicorns sasquatch
    print foo.baz                                        
    # prints baz unicorns sasquatch
    print foo2.bar                                       
    # prints other unicorns sasquatch
    

    While property in a factory function may be fine for your toy example, it sounds like maybe you need more control for your real use case.

提交回复
热议问题