【发布时间】: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