0

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

2
  • 1
    Because the function is a method of the class, you have to access it using the self keyword. It's probably a good idea for you to have a look at a basic python class tutorial, as this is a pretty key feature Commented May 27, 2021 at 16:53
  • PS, I'm not sure if this is intended or not, but Graphs.fetch_values returns (temp, mois, hum, DT) and you are assigning that to new_DT, new_temp, new_hum, new_mois which has the variables in a different order...? Commented May 27, 2021 at 16:55

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this but im getting an error now while calling the function: "NameError: name 'self' is not defined" @Riko_md

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.