【发布时间】:2021-05-27 16:47:24
【问题描述】:
我设计了一个“Graphs”类并初始化了 4 个列表来存储我从 firebase 数据库中获取的值。我创建了一个函数“fetch_values”来获取值并将它们存储在相应的列表中。那部分工作得很好。但是当我试图在同一个类“Graphs”中的另一个函数“store_values”中访问这些更新列表时,我收到一个错误 “NameError: name 'fetch_values' is not defined” 这个函数store_values 应该获取这些列表并将值保存在我文件夹中的 CSV 文件中。但是,它不起作用。 我希望我的问题很清楚,任何帮助将不胜感激!
这是我的课:
class Graphs(object):
def fetch_values():
temp=[]
mois=[]
hum=[]
DT=[]
def fetch():
LY_project=firebase.FirebaseApplication("https://ly-project-b1f1c-default-rtdb.firebaseio.com/",None)
result=LY_project.get("Values","")
#time=pd.to_datetime((result["LastIrrD"] +" "+ result["LastIrrT"]),infer_datetime_format=True)
now=dt.datetime.now().strftime("%H:%M:%S")
temp.append(result["Temperature"])
mois.append(result["Moisture"])
hum.append(result["Humidity"])
DT.append(now)
#DT.append(time)
#print(time)
print(len(DT))
print(result)
#-------------------------------------------Start Fetch-------------------------------------------#
print ("Fetching Values...\n")
n=5 #Number of readings
interval=2 #Interval between readings
safety=n # Safely space added to avoid overwriting of values
rt = RepeatedTimer(interval, fetch) # it auto-starts, no need of rt.start()
try:
sleep(n*interval+safety) # your long-running job goes here...
finally:
rt.stop() # try/finally block to make sure the program ends!
print("\nValues fetched successfully.")
return temp,mois,hum,DT
#----------------------------------------------------------------Store the fetched values---------------------------------------------------------------------#
def store_values():
new_DT,new_temp,new_hum,new_mois=fetch_values()
#Save data to csv file
fields = ['Date-Time', 'Soil Moisture', 'Temperature', 'Humidity']
rows = [new_DT, new_mois, new_temp,new_hum]
dict = {'Date-Time': new_DT, 'Soil Moisture': new_mois, 'Temperature': new_temp, "Humidity": new_hum}
df = pd.DataFrame(dict)
display(df)
#df.to_csv("readings4.csv")
“start fetch 下的代码工作正常,我能够获取列表中的值。但是,当我在下面的函数 (store_values) 中调用这些列表时,出现错误。”
请帮忙!
这是我得到的错误: enter image description here
【问题讨论】:
-
因为函数是类的方法,所以你必须使用
self关键字来访问它。看一个基本的 Python 类教程可能对你来说是个好主意,因为这是一个非常关键的特性 -
PS,我不确定这是否有意,但
Graphs.fetch_values返回(temp, mois, hum, DT),您将其分配给new_DT, new_temp, new_hum, new_mois,其中变量的顺序不同... ?
标签: python function class function-call