首页 > 解决方案 > Python 遗产

问题描述

我有一个听起来可能很奇怪的问题,但我想在我的孩子中调用我父类的函数。

我使用MyChildtkinter 并且已经从框架中继承。

前任:

class MyParent:
    def __init__(self):
        do_things()

    def myfunction(self):
        child_class = MyChild()

    def call_me(self):
        print("I'm here!")

class MyChild:
    def __init__(self):
        do_things()

    def my_call(self):
        #here call the call_me function

在这里,我希望在MyChild类中调用该函数时my_call,它会调用该类的函数。我只想知道是否以及如何调用函数call_meMyParentcall_memy_callMyparent.call_me()

标签: pythontkinter

解决方案


根据您问题中的代码,您的孩子必须被告知其父母是什么。这通常在您创建孩子时完成。子级可以保留一个引用,以便在需要调用父级上的方法时可以使用它。

例子:

class MyParent:
    def myfunction(self):
        child_class = MyChild(parent=self)

    def call_me(self):
        print("I'm here!")

class MyChild:
    def __init__(self, parent):
        self.parent = parent
        do_things()

    def my_call(self):
        self.parent.call_me()

推荐阅读