python - 父引用问题 python

标签 python class wxpython

我有一个 wxPython 应用程序,其中包含如下代码。我想设置 MyFrame 类的属性值,但无法引用它。
我怎样才能让这段代码工作?

class MyFrame1(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)
        self.gauge_1 = wx.Gauge(self, -1)
        self.notebook_1=myNotebook(self, -1)

class myNotebook(wx.Notebook):
    def __init__(self, *args, **kwds):
        wx.Notebook.__init__(self, *args, **kwds)
        self.other_class_1=other_class()
        self.other_class_1.do_sth()

class other_class(object):
    def do_sth(self):
        gauge_1.SetValue(value) #doesn't work of course, how do I do this?

最佳答案

我认为子 UI 元素的设计者如果对其父元素有具体的了解,这有点糟糕。这是一种向后的设计。 children 通常应该有某种方式发出信号或引发事件并让适当的听众使用react。但是,如果这确实是您想要做的,那么您可能想要获取父项并直接对其进行操作...

注意:不要采用这种方法。我正在说明为什么设计有问题......

首先,您甚至无法按照代码的结构方式执行此操作,因为 other_class 没有对父级的引用。它是一个通用实例。所以你必须做类似的事情......

class other_class(object):

    def __init__(self, parent):
        self.parent = parent

在你的笔记本类(class)中...

class myNotebook(wx.Notebook):
    def __init__(self, *args, **kwds):
        wx.Notebook.__init__(self, *args, **kwds)
        # note here we pass a reference to the myNotebook instance
        self.other_class_1 = other_class(self)
        self.other_class_1.do_sth()

一旦你的 other_class 现在知道了它的父类,你就必须让父类的父类拥有 MyFrame1 实例...

class other_class(object):

def __init__(self, parent):
    self.parent = parent

def do_sth(self, value):
    self.parent.GetParent().gauge_1.SetValue(value) 

你现在明白为什么这是一个糟糕的设计了吗?多个级别的对象必须假定了解父结构。

我不熟悉 wxPython,所以我无法向您提供具体信息,但这里有一些可以考虑的通用方法:

  1. 确定 other_class 的真正作用是什么。如果它确实要对 MyFrame1 的子级进行操作,那么该功能属于 MyFrame1,因此它可以了解这些成员。
  2. 如果other_class是一个wx对象,它可以在调用do_sth()方法时发出一个wx.Event。您可以在 MyFrame1 或 Notebook 级别绑定(bind)该事件,并在处理程序中执行所需的任何工作。

关于python - 父引用问题 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9642012/

相关文章:

Python去重记录——dedupe

C++ 成员变量

python - wxPython:单选按钮如何在我关闭框架时记住我的选择

python - 将文本复制到剪贴板的平台独立工具

python - Unix:有没有Python脚本不断运行的最佳实践?

python - 如何创建只读插槽?

language-agnostic - 程序员应该在一个文件中放入多少个类?

c# - 为什么绑定(bind)到结构不起作用?

wxpython - 如何在 wxPython 3.0 (Phoenix) 中制作 wx.Frame 模态

python - python可以一次性给不同的键赋同一个值吗?