从另一个类调用__init__中的类函数?

时间:2018-02-15 23:13:34

标签: python function class tkinter

首先要注意的是,我正在使用tkinter。每个'child'类都有一些独特的小部件和函数,但是每个子类都从父类继承了小部件和函数(这里定义了背景颜色等东西,因为它在每个屏幕上都是相同的)。当用户单击某些按钮时,将破坏当前类的屏幕,并调用下一个类。话虽如此,如果我有这样的父类:

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

如何在change()函数中调用back()函数?我尝试了'child.change',但是这返回了一条错误消息,指出没有'child'属性称为'change'。

1 个答案:

答案 0 :(得分:1)

解决方案是使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()
相关问题