Python: Generic getters and setters

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

    Using getattribute and setattr you can define this for all attributes past and future.

    class Foo(object):                                                                                                                           
    
      x = 3 
    
      def __getattribute__(self, attr):
        return str(object.__getattribute__(self, attr)) + ' sasquatch'
    
      def __setattr__(self, attr, value):
        object.__setattr__(self, attr, str(value) + ' unicorn')
    
    print Foo.x
    f = Foo()
    print f.x 
    f.y = 4 
    print f.y 
    

    This prints:

    3
    3 sasquatch
    4 unicorn sasquatch
    

提交回复
热议问题