python property how to somehow overload += on a setter

时间:2017-05-03 14:29:06

标签: python

I have a question regarding the use of decorators. I am coding a class function that drive a motor stage. Here is a skeleton:

class Stage(object):    
    def get_position(self):
        print("Getting Position")
        return 0

    def set_position_absolute(self, value):
        print("Setting Position Absolute %f"%value)

    def set_position_relative(self, value):
        print("Setting Position Relative %f"%value)

    @property
    def x(self):
        return self.get_position()

    @x.setter
    def x(self,value):
        self.set_position_absolute(value)

The stage position (let's say x), can be:

  • set in an "absolute" way with a value: the new x must be equal to the value (x=value).
  • set in an "relative" way with a value: the new x is equal to former_value + value ( x+= value)

What I would like to do, is to use the decorator in such a way that if I use something like:

stage.x += 10

the setter will use only the method set_position_relative(10), instead of calling both get_position() and set_position_absolute(10) (as it is the case now).

0 个答案:

没有答案