Home > Enterprise >  I am creating a backend for a habit tracker using OOP but I get a "NameError: name not defined
I am creating a backend for a habit tracker using OOP but I get a "NameError: name not defined

Time:09-29

This backend for habit tracking app gives a NameError "name does not exist". The values are passed to the class but when create is called, it throws a NameError.

class habit(object):
    def __init__(self, name, period):
        self.name = name
        self.period = period
        #self.hab_oper = hab_oper
        
    def create(self):
        self.name = name
        self.period = period
        #self.hab_oper = hab_oper
        day = ftime(period)
        db = sqlite3.connect("../habit/habit.db")
        cur = db.cursor()
    
        #query to incert input name to create habit in database of selected pereiod
        cur.execute(f"INSERT INTO {period} ('name', 'first') VALUES ('{name}',{day})")

        db.commit()     #makes changes to database permanent
        cur.close()     #closes connection to database
        db.close()
    
        print(f" Habit name is {name} in {period}")

cre_hab = habit("reading", "daily")
cre_hab.create()

CodePudding user response:

These two lines in create:

self.name = name
self.period = period

Are backwards: you meant:

name =self.name
period = self.period
  • Related