advik Maniar
advik Maniar

Reputation: 9

Access variables from a function in another function inside a same python class

I have designed a class "Graphs" and have initialized 4 lists to store the values that I fetch from the firebase database. I have created a function "fetch_values" to fetch the values and store them in the respective lists. That part is working perfectly. But when I'm trying to access those updated lists in another function "store_values" inside the same class "Graphs", I am getting an error "NameError: name 'fetch_values' is not defined" This function store_values is supposed to take those lists and save the values in a CSV file in my folder. However, it's not working. I hope my question is clear, any help would be appreciated!

This is my class:

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")

The code under "start fetch is working fine and I am able to fetch the values in the lists. However, when I call those lists in the function below that (store_values), I am getting an error."

Please help!

This is the error I am getting: enter image description here

Upvotes: 0

Views: 56

Answers (1)

Riko_md
Riko_md

Reputation: 11

You should add self keyword to all lists in class functions. Here is an example:

class Dog:

    tricks = []

    def add_trick(self, trick):
        self.tricks.append(trick)

It is good enough to work, but a correct implementation of a class should look like this:

class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []

    def add_trick(self, trick):
        self.tricks.append(trick)

Upvotes: 1

Related Questions