首页 > 解决方案 > 我正在使用 OOP 为习惯跟踪器创建后端,但出现“NameError:调用 create 方法时未定义名称”

问题描述

这个习惯跟踪应用程序的后端给出了一个 NameError “名称不存在”。这些值被传递给类,但是当调用 create 时,它​​会抛出 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()

标签: pythonoop

解决方案


创建中的这两行:

self.name = name
self.period = period

倒退:你的意思是:

name =self.name
period = self.period

推荐阅读