python - 从同一个python类中另一个函数中的函数访问变量
问题描述
我设计了一个“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) 中调用这些列表时,出现错误。”
请帮忙!
这是我得到的错误: 在此处输入图像描述
解决方案
您应该将self
关键字添加到类函数中的所有列表中。这是一个例子:
class Dog:
tricks = []
def add_trick(self, trick):
self.tricks.append(trick)
工作起来已经足够好了,但是一个类的正确实现应该是这样的:
class Dog:
def __init__(self, name):
self.name = name
self.tricks = []
def add_trick(self, trick):
self.tricks.append(trick)
推荐阅读
- maven - 如何设置 -Xlint:unchecked 内部 spring-boot-maven-plugin
- reactjs - Material UI Tooltip - 自定义翻转行为
- python - 如何为不同的租户使用不同的文本和徽标 - django-tenants
- java - Java 代码中的 Selenium Grid Hub 和 Node
- javascript - 如何避免 HTML5 Canvas 中随机生成的坐标重叠?
- python - 为什么熊猫滚动意味着居中窗口
- css - 如何使用 Elementor 激活字体连字
- javascript - Javascript - 将数组转换为递归对象
- python - docker容器中python应用程序的虚拟内存不足
- html - 根据屏幕分辨率更改下拉菜单的宽度