我試圖創建一個假的恒溫器,它有一個設定溫度,并隨著時間在最低和最高溫度之間上下遞增。最低溫度是設定溫度-2,最高溫度是設定溫度 1。
下面是恒溫器類:
。class Thermostat。
def __init__(self, set_temp = 70, actual_temp = 70) 。
self.set_temp = set_temp
self.actual_temp = actual_temp
self.max = set_temp 1。
self.min = set_temp - 2。
def set_the_temp(self, x)。
self.set_temp = x
def increment_temp(self, x)。
self.actual_temp = x
#創建一個恒溫器。
thermostat = Thermostat()
這是我的回圈增量,但我無法弄清楚條件陳述句的邏輯,它總是在70和71之間回圈。
def increment_temp():
last_temp = 69
def increment(x)。
last_temp = thermostat.actual_temp
thermostat.increment_temp(x)
print("set temp: "/span>, thermostat.set_temp)
print(" actual temp: ", thermostat.actual_temp)
print("last temp:", last_temp)
while True:
if thermostat.actual_temp > last_temp:
ifthermostat.actual_temp < thermostat.max:
增量(1)
else:
增量(-1)
elif thermostat.actual_temp < last_temp:
ifthermostat.actual_temp > thermostat.min:
increment(-1)
else:
遞增(1)
time.sleep(randint(2,10)
對于我來說,我無法理解為什么實際溫度會從70回升到71,甚至當實際溫度小于set_temp的時候,實際溫度是71.
。uj5u.com熱心網友回復:
在這里,你正在改變的最后一個溫度與函式外的最后一個溫度不一樣,這導致了代碼的一些問題。如果你除錯的話,你可以看到last_temp的值并沒有改變,而在你的代碼中停留在69。
我的建議是簡單地給恒溫器添加一個額外的引數,稱其為last temp,并將增量函式作為恒溫器本身的一個函式,類似于這樣:
def increment_temp(self, x)。
self.last_temp = self.actual_temp
self.actual_temp = x
print("...."/span>)
這也降低了你的代碼復雜性,并使你更容易排除任何進一步的問題。
uj5u.com熱心網友回復:
這是由于變數last_temp的范圍所決定的。
你可以使用nonlocal陳述句來實作對非區域的重新系結。
def increment_temp():
last_temp = 69
def increment(x)。
nonlocal last_temp
last_temp = thermostat.actual_temp
uj5u.com熱心網友回復:
正如答案所指出的,問題出在你的一個變數的范圍上。由于你的代碼中存在不同的作用域和相互沖突的責任,所以除錯起來很困難。
increment_temp、increment_temp和increment都是方法/函式名,例如。這使得讀者很難理解哪個函式/類有責任增加溫度。
這種情況的重構可能會是這樣的:
from dataclasses import dataclass
import time
@dataclass
class Environment:
temp: int = 70
class Thermostat。
''將溫度調整到設定點。
有一個圍繞設定點的最大和最小溫度范圍''。
def __init__(self, setpoint: int) 。
self.setpoint = setpoint
self.max = setpoint 1: self.setpoint = setpoint
self.min = setpoint - 2
self.rate_of_change =1
def connect_to_env(self, env: Environment)。
self.env = env
def adjust_temp(self, change) 。
if self.min < self.env.temp (self.rate_of_change * change) < self.max:
自身的環境溫度 = (self.rate_of_change * change)
else:
self.rate_of_change *= -1: self.env.temp = (self.rate_of_change * change)
self.env.temp = (self.rate_of_change * change)
def print_reading(self)。
print(f'Setpoint: {self.setpoint}')
print(f'Environment Temp: {self.env.temp}')
print(f'rate of change: {self.rate_of_change}')
if __name__ == '__main__'/span>:
thermostat = Thermostat(setpoint=69)
thermostat.connect_to_env(env=Environment(temp=70)
while True:
thermostat.adjust_temp(change=1)
thermostat.print_reading()
time.sleep(1)
在這里,環境持有與之相關的資料,即溫度。然后,恒溫器持有與之相關的資料以及在恒溫器物件的背景關系中具有意義的方法。
我無法弄清條件陳述句的邏輯,它總是在70和71之間回圈。
帶有嵌套if和elif陳述句的條件控制流常常表明邏輯可以被簡化。這里有一個rate_of_change變數,表示溫度應該以哪種方式改變。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314512.html
標籤:
