Home > Back-end >  Do class in python need parameter when we call it?
Do class in python need parameter when we call it?

Time:03-14

I am new to python, actually new to programming too, and I am recently working on a simple project with Tkinter. In this project, I was trying to create a force attention window and I finally got the answer from this page. The main codes are as follows:

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()

It worked though, one thing that I am still concerning is that why he specified a parameter in a class APP:

class App(tk.Tk):

However, there is nothing pass in the class when he called it:

    app = App()

Can anyone answer it, or just give me some keyword that I can go search specifically. I have read some of the tutorials about class in python, but none of them mention it.

CodePudding user response:

This is called inheritance. All parameters for creating an object of the class, like you did here: app = App(), are in the __init__ method.

class App(tk.Tk): This part is not a parameter. Instead, this indicates that the App class inherits methods from the tk.Tk class. In essence, this is what turns your App class into a Tkinter application. Without it, you wouldn't have any of the functionality that Tkinter provides. Observe how at the bottom of your code, you create the app and then call app.mainloop(). Note that your App class has no mainloop method. It actually comes from the inherited tk.Tk class.

That said, this is a major topic in most languages so I don't doubt you'll find tons of resources to learn further if you simply search for "Python inheritance".

  • Related