Python类Menu方法调用报错:缺少必填位置参数self
问题根因
报错直接来源是你类定义最末尾顶格写的裸调用Menu(),和你在__init__里写的调用逻辑没关系。
你定义的Menu是SupermarketDAO类的实例方法,这类方法必须绑定类的实例对象才能调用,调用时Python会自动把实例对象传给self参数。而你最后那行Menu()是顶格书写的,和class SupermarketDAO:这行处于同一缩进层级,根本不属于类内部的代码,Python执行完类定义后就会直接跑这行,尝试全局调用Menu,既没有绑定实例,也没手动传self参数,自然会抛出缺位置参数的错误。
你之前试的self.Menu = Menu()写法完全是错的:这行是尝试给实例绑定一个叫Menu的属性,赋值时还是直接全局调用了未绑定实例的Menu方法,照样会触发同样的报错。
修复步骤
- 直接删掉类定义最末尾那行游离在类外的
Menu(),这行删掉后当前的类型错误会直接消失。 - 调整
__init__里的调用顺序:建议先执行self.startUp()完成数据库连接、初始化表结构等前置操作,再调用self.Menu()进入交互菜单,避免没连库就触发数据库操作报错。 - 类定义完成后,不要在类内部直接启动逻辑,在代码全局层级通过实例化类对象来启动程序。
修复后参考代码
import sys class SupermarketDAO: def __init__(self): self.count = None self.option = None self.barcode = None self.cursor = None # 补全你的数据库游标获取逻辑 self.dbCreated = False _continue = True self.startUp() # 先完成初始化 self.Menu() # 再进菜单 def Menu(self): print("[1] Add products to Database") print("[2] List all products in Database, based on product bar-code") print("[3] List all transactions(Ascending order of date of transaction") print("[4] Display Barchart of Products sold by quantity") print("[5] Display an Excel report of all transactions") print("[6] EXIT") option = int(input("Enter your option:")) while option != 0: if option == 1: print("go to Add products to Database") # 注意提前定义products变量,否则会报未定义错误 # self.addProductToDB(products) break elif option == 2: print("go to List all products in Database") # self.listAllProducts() break elif option == 3: print("go to List all transactions") # self.listAllTransactions() break elif option == 4: print("go to Display Barchart of Products sold by quantity") # self.displayBarchartOfProductsSold() break elif option == 5: print("go to Display an Excel report of all transactions") # self.addProductToDB(products) break elif option == 6: print("EXIT") sys.exit() else: print("invalid option!") break # 这里补全你引用的所有实例方法:startUp、addProductToDB、listAllProducts等 def startUp(self): # 补初始化逻辑 pass # 程序入口,实例化对象启动 if __name__ == "__main__": dao = SupermarketDAO()
额外提醒
- 你当前的菜单逻辑执行完一次选项就会
break退出循环,用户选完一次功能程序就会结束,如果要实现重复选单的效果,需要把用户输入选项的代码移到while循环内部。 - 代码中引用的
products变量、所有被调用的类方法都需要提前实现,否则运行时会抛出未定义/方法不存在的错误。 - 按照Python编码规范,方法名建议使用小写下划线命名(比如
menu而不是Menu),避免和类名的大驼峰命名混淆,这个属于规范建议,不强制。
内容的提问来源于stack exchange,提问作者Paige
相关产品推荐
相关产品推荐

