Elegant way to add functionallity to previously defined functions
        Posted  
        
            by 
                Bastiaan
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Bastiaan
        
        
        
        Published on 2012-06-07T22:23:29Z
        Indexed on 
            2012/06/07
            22:40 UTC
        
        
        Read the original article
        Hit count: 220
        
How to combine two functions together
I have a class controlling some hardware:
class Heater()
    def set_power(self,dutycycle, period)
       ...
    def turn_on(self)
       ...
    def turn_off(self)
And a class that connects to a database and handles all data logging fuctionallity for an experiment:
class DataLogger()
    def __init__(self)
        # Record measurements and controls in a database
    def start(self,t)
        # Starts a new thread to aqcuire and reccord measuements every t secconds
Now, in my program recipe.py I want to do something like:
        log = DataLogger()
        @DataLogger_decorator
        H1 = Heater()
        log.start(60)
        H1.set_power(10,100)
        H1.turn_on()
        sleep(10)
        H1.turn_off()
        etc
Where all actions on H1 are recorded by the datalogger. I can change any of the classes involved, just looking for an elegant way to do this. Ideally the hardware functions remain separated from the database and DataLogger functions. And ideally the DataLogger is reusable for other controls and measurements.
© Stack Overflow or respective owner