Multiple properties with similar getter/setter functions?

前端 未结 2 2001
别跟我提以往
别跟我提以往 2021-01-07 14:32

What is the cleanest way to define a class with a large number of properties, each of which calls the same setter function with a different parameter?

Below is what

相关标签:
2条回答
  • 2021-01-07 14:58

    Perhaps you can do this:

    def setter(self, address, value):
        if address == self.red_LED_address:
            attr = '_red_LED_status'
        if address == self.blue_LED_address:
            attr = '_blue_LED_status'
        if address == self.green_LED_address:
            attr = '_green_LED_status'
        self.TalkToHardware(address, value)
        setattr(self, attr, value) ## does this: self._XXX_LED_address = value
    

    This is a catch-all function for all of your LED setter functions.

    I hope this was helpful!

    0 讨论(0)
  • 2021-01-07 15:08

    You could create a function that simply defines and returns the needed property class instance and then use it to define the class, thus getting rid of all that repetitive code .

    (In case it's not obvious, the LED_property() function in the code below corresponds to the one named some_magic() in your question.)

    class Hardware_Controller(object):
        def LED_property(color_name):
            """ Create and return a property for the given color_name. """
            address_name = color_name + '_LED_address'
            storage_name = '_' + color_name + '_LED_status'
    
            @property
            def prop(self):
                return getattr(self, storage_name)
    
            @prop.setter
            def prop(self, value):
                address = getattr(self, address_name)
                self.TalkToHardware(address, value)
                setattr(self, storage_name, value)
    
            return prop
    
        red_LED = LED_property('red')
        blue_LED = LED_property('blue')
        green_LED = LED_property('green')
    
        def __init__(self):
            self.red_LED_address = 0
            self.blue_LED_address = 1
            self.green_LED_address = 2
    
        def TalkToHardware(self, address, value):
            print('Sending %i to address %i' % (value, address))
    
        del LED_property  # Function isn't needed outside class definition.
    
    
    if __name__ == "__main__":
        a = Hardware_Controller()
        a.red_LED = 1     # -> Sending 1 to address 0
        a.green_LED = 0   # -> Sending 0 to address 2
        print(a.red_LED)  # -> 1
    

    Similar to recipe "9.21 Avoiding Repetitive Property Methods" in the Python Cookbook, Third Edition by David Beazley & Brian Jones (2013). I found a PDF of the entire book (8.8 Mb), the recipe's on page 382.

    0 讨论(0)
提交回复
热议问题