python - Python 遗产
问题描述
我有一个听起来可能很奇怪的问题,但我想在我的孩子中调用我父类的函数。
我使用MyChild
tkinter 并且已经从框架中继承。
前任:
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_me
MyParent
call_me
my_call
Myparent.call_me()
解决方案
根据您问题中的代码,您的孩子必须被告知其父母是什么。这通常在您创建孩子时完成。子级可以保留一个引用,以便在需要调用父级上的方法时可以使用它。
例子:
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()
推荐阅读
- javascript - i 在 for 循环中的行为不是我所期望的
- python - 如何从字典中的列表(每个索引独立)写入条目列表?
- c - C中的反转字符串
- android - RecyclerView 在另一个具有相同布局管理器的 RecyclerView 内部不滚动
- hadoop - 当我们从 HDFS 将数据加载到 Hive 表中时,它会从源目录(HDFS)中删除文件
- sql - 如何在 SAP HANA DB 中列出当前用户的所有可选表
- prometheus - 如何使用 prometheus alertmanager 在工作时间以外抑制警报?
- javascript - 为什么watcher会触发两次?
- laravel - Laravel 5.8 个人用户会话生命周期的登录自定义
- laravel - 如何修复 Laravel 页面未找到错误?