简体   繁体   中英

Initialize function variable once & change variable value when function is called

Language : Python

I want the value of a variable to be initialized to zero at the start of the execution. This variable is used in a function & its value may also get changed within the function. But I do not want the value of this variable to reset to zero whenever a function call is made. Instead, its value should be equal to the updated value from its previous function call.

Example:
get_current() is constantly returning a different value when it is called. ctemp is initially zero. In the first function call get_current_difference() will return cdiff & then update the value of ctemp such that ctemp = current . In the second function call, the value of ctemp should not be zero. Instead, it should be equal to the updated value from the first function call.

import serial
arduino = serial.Serial('/dev/ttyACM1',9600)
ctemp = 0

def get_current():
    line = arduino.readline()
    string = line.replace('\r\n','')
    return string

def get_current_difference():
    global ctemp
    current = get_current()
    cdiff = float(current) - ctemp
    return cdiff
    ctemp = current

while 1:
    current = get_current_difference()
    print(current)

You return before setting value of ctemp

return cdiff
ctemp = current

must become

ctemp = current
return cdiff

You are describing mutable state and a function to modify it, which is what classes are for.

class Temperature:
    def __init__(self, arduino):
        self.ctemp = 0
        self.arduino = arduino

    def current(self):
        line = self.arduino.readline()
        return line.replace('\r\n', '')

    def difference(self):
        current = self.current()
        cdiff = float(current) - self.ctemp
        self.ctemp = current
        return cdiff

t = Tempurature(serial.Serial('/dev/ttyACM1', 9600)
while True:
    print(t.difference())

Using a class scales if, for example, you have multiple temperature monitors to work with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM