[英]Call a class function in __init__ from another class?
首先要注意的是,我正在使用tkinter。 每个“子”类都有一些唯一的窗口小部件和功能,但是每个子类都从父类继承这些窗口小部件和功能(在这里定义了背景色之类的东西,因为在每个屏幕上都是一样的)。 当用户单击某些按钮时,当前类的屏幕将被破坏,并调用下一个类。 话虽如此,如果我有一个像这样的父类:
class parent:
def __init__(self):
def back():
if (someCondition == True):
#some algorithm to go back, by deleting the current screen and popping the previous screen off a stack.
else:
change()
#Algorithm to create main window
self.back = Button(command=back)
像这样的孩子班
class child(parent):
def __init__(self):
parent.__init__(self)
def change()
#algorithm to change the contents of the screen, because in this unique case, I don't want to destroy the screen and call another one, I just want the contents of this screen to change.
#Some algorithm to put unique widgets and such on this screen
如何从back()
函数中调用change()
back()
函数? 我尝试了'child.change',但这返回了一条错误消息,指出没有名为'change'的'child'属性。
解决的办法是back
正常方法。 父母可以以正常方式调用孩子的方法。
class Parent(object):
def back(self):
print("in parent.back()")
self.change()
class Child(Parent):
def change(self):
print("in child.change()")
# create instance of child
child = Child()
# call the back function:
child.back()
上面的代码产生以下输出:
in parent.back()
in child.change()
如果愿意,可以使Parent.change()
引发错误,以强制孩子实现它:
class Parent(object):
...
def change(self):
raise Exception("Child must implement 'change'")
class MisfitChild(Parent):
pass
有了上述内容,以下内容将引发错误:
child = MisfitChild()
child.back()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.