简体   繁体   English

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

[英]Call a class function in __init__ from another class?

First important note, I'm using tkinter. 首先要注意的是,我正在使用tkinter。 Each 'child' class has some unique widgets and functions, but every child class inherits the widgets and functions from the parent class (stuff like the background colour is defined here, because it's the same on every screen). 每个“子”类都有一些唯一的窗口小部件和功能,但是每个子类都从父类继承这些窗口小部件和功能(在这里定义了背景色之类的东西,因为在每个屏幕上都是一样的)。 When the user clicks certain buttons, the current class' screen is destroyed, and the next class is called. 当用户单击某些按钮时,当前类的屏幕将被破坏,并调用下一个类。 With that said, if I have a parent class like this: 话虽如此,如果我有一个像这样的父类:

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)

And a child class like this 像这样的孩子班

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

How could I call the change() function from within the back() function? 如何从back()函数中调用change() back()函数? I tried 'child.change', but this returned an error message stating there was no attribute of 'child' called 'change'. 我尝试了'child.change',但这返回了一条错误消息,指出没有名为'change'的'child'属性。

The solution is to make back a normal method. 解决的办法是back正常方法。 The parent can call methods of the child in the normal way. 父母可以以正常方式调用孩子的方法。

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()

The above code yields the following output: 上面的代码产生以下输出:

in parent.back()
in child.change()

If you prefer, you can make Parent.change() throw an error, to force the child to implement it: 如果愿意,可以使Parent.change()引发错误,以强制孩子实现它:

class Parent(object):
    ...
    def change(self):
        raise Exception("Child must implement 'change'")

class MisfitChild(Parent):
    pass

With the above, the following will throw an error: 有了上述内容,以下内容将引发错误:

child = MisfitChild()
child.back()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM