调用python中的class需要参数吗?
Do class in python need parameter when we call it?
我是 python 的新手,实际上也是编程的新手,我最近正在使用 Tkinter 开发一个简单的项目。在这个项目中,我试图创造一个力注意力window,我终于得到了的答案。主要代码如下:
import tkinter as tk
class App(tk.Tk):
TITLE = 'Application'
WIDTH, HEIGHT, X, Y = 800, 600, 50, 50
def __init__(self):
tk.Tk.__init__(self)
tk.Button(self, text="open popout 1", command=self.open1).grid()
tk.Button(self, text="open popout 2", command=self.open2).grid()
def open1(self):
PopOut1(self)
def open2(self):
# .transient(self) ~
# flash PopOut if focus is attempted on main
# automatically drawn above parent
# will not appear in taskbar
PopOut2(self).transient(self)
if __name__ == '__main__':
app = App()
app.title(App.TITLE)
app.geometry(f'{App.WIDTH}x{App.HEIGHT}+{App.X}+{App.Y}')
# app.resizable(width=False, height=False)
app.mainloop()
虽然有效,但我仍然担心的一件事是他为什么在 class APP 中指定了一个参数:
class App(tk.Tk):
但是,他调用的时候class里面什么也没有传:
app = App()
谁能回答一下,或者给我一些关键字,我可以专门去搜索。我在 python 中阅读了一些关于 class 的教程,但其中 none 提到了它。
这叫做继承。创建 class 对象的所有参数,就像您在此处所做的那样:app = App()
,都在 __init__
方法中。
class App(tk.Tk):
这部分不是参数。相反,这表明 App class 继承了 tk.Tk class 的方法。从本质上讲,这就是将您的 App class 变成 Tkinter 应用程序的原因。没有它,您将无法使用 Tkinter 提供的任何功能。观察代码底部如何创建应用程序,然后调用 app.mainloop()
。请注意,您的 App class 没有 mainloop 方法。它实际上来自继承tk.Tk class.
也就是说,这是大多数语言中的一个主要主题,所以我相信如果您只需搜索“Python 继承”,您就会找到大量资源来进一步学习。
我是 python 的新手,实际上也是编程的新手,我最近正在使用 Tkinter 开发一个简单的项目。在这个项目中,我试图创造一个力注意力window,我终于得到了
import tkinter as tk
class App(tk.Tk):
TITLE = 'Application'
WIDTH, HEIGHT, X, Y = 800, 600, 50, 50
def __init__(self):
tk.Tk.__init__(self)
tk.Button(self, text="open popout 1", command=self.open1).grid()
tk.Button(self, text="open popout 2", command=self.open2).grid()
def open1(self):
PopOut1(self)
def open2(self):
# .transient(self) ~
# flash PopOut if focus is attempted on main
# automatically drawn above parent
# will not appear in taskbar
PopOut2(self).transient(self)
if __name__ == '__main__':
app = App()
app.title(App.TITLE)
app.geometry(f'{App.WIDTH}x{App.HEIGHT}+{App.X}+{App.Y}')
# app.resizable(width=False, height=False)
app.mainloop()
虽然有效,但我仍然担心的一件事是他为什么在 class APP 中指定了一个参数:
class App(tk.Tk):
但是,他调用的时候class里面什么也没有传:
app = App()
谁能回答一下,或者给我一些关键字,我可以专门去搜索。我在 python 中阅读了一些关于 class 的教程,但其中 none 提到了它。
这叫做继承。创建 class 对象的所有参数,就像您在此处所做的那样:app = App()
,都在 __init__
方法中。
class App(tk.Tk):
这部分不是参数。相反,这表明 App class 继承了 tk.Tk class 的方法。从本质上讲,这就是将您的 App class 变成 Tkinter 应用程序的原因。没有它,您将无法使用 Tkinter 提供的任何功能。观察代码底部如何创建应用程序,然后调用 app.mainloop()
。请注意,您的 App class 没有 mainloop 方法。它实际上来自继承tk.Tk class.
也就是说,这是大多数语言中的一个主要主题,所以我相信如果您只需搜索“Python 继承”,您就会找到大量资源来进一步学习。