我在python中遇到了多重继承问题。使用python的super()命令给我一个"达到的最大递归深度"。 代码:
class program(object):
def back(self):
if self.currentWin == "welcome":
self.welcomeWindow.root.destroy()
exit(0)
def login(self): print("login")
def register(self): print("register")
def __init__(self):
super().__init__()
self.currentWin = "welcome"
self.welcomeWindow = welcomewin()
class welcomewin(program):
def __init__(self):
super().__init__()
self.root=tkinter.Tk()
tkinter.Button(self.root,text="Exit",command=self.back).grid(row=1,column=2)
if __name__=="__main__": program()
这里的问题是我试图在welcomewin中设置一个按钮,该按钮调用程序的后退功能,它继承自程序。但是,它没有继承back()依赖的currentwin
变量来决定做什么。
如果我运行此代码,则会出现以下错误:
File "E:/Python project/test.py", line 15, in __init__
super().__init__()
File "E:/Python project/test.py", line 11, in __init__
self.welcomeWindow = welcomewin()
File "E:/Python project/test.py", line 15, in __init__
super().__init__()
File "E:/Python project/test.py", line 11, in __init__
self.welcomeWindow = welcomewin()
File "E:/Python project/test.py", line 15, in __init__
super().__init__()
File "E:/Python project/test.py", line 11, in __init__
self.welcomeWindow = welcomewin()
RuntimeError: maximum recursion depth exceeded while calling a Python object
>>>
答案 0 :(得分:1)
您收到此错误是合乎逻辑的。您从welcomewin
继承program
并在welcomewin
__init__()
函数中创建新的program
对象。这意味着将创建一个新的welcomewin
对象,再次调用__init__()
函数,这将永远持续下去。
简单的解决方案:不要从程序继承welcomewin。
答案 1 :(得分:-2)
你在init中调用了init,它创建了一个无限循环。
def __init__(self):
super().__init__()
这应该有效
def __init__(self):
super(program)