【问题标题】:Call a class function in __init__ from another class?从另一个类调用 __init__ 中的类函数?
【发布时间】:2018-02-15 23:13:33
【问题描述】:

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

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

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

【问题讨论】:

  • 嵌套函数不能直接访问。如果需要直接调用,为什么要嵌套在__init__里面呢?
  • 您将back 作为函数嵌套在__init__ 中。这使它成为该函数中的本地名称only,并且仅在__init__ 运行时存在。将您的函数移出 __init__ 并使其成为适当的方法或模块顶层的函数,以重用它们。
  • 好的,我明白了!你的意思是我可以让change() 成为一个类函数,甚至可以从init 中调用它作为child.change()。好的,这行得通,谢谢大家。
  • 根本没有理由创建嵌套函数。如您所见,它使开发变得更加困难。
  • @nae:是的,我主要指的是这个具体的例子。嵌套函数对于解决有限的问题子集很有用。

标签: python function class tkinter


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-10
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 2023-04-04
    • 2016-01-09
    • 1970-01-01
    相关资源
    最近更新 更多