Reputation: 77
I'm trying to make a tkinter GUI with multiple frames and when creating the class I am including the __init__ method
.
Do I have to pass self
into this or is it implied?
I am watching a tutorial for tkinter (https://www.youtube.com/watch?v=A0gaXfM1UN0&list=PLQVvvaa0QuDclKx-QpC9wntnURXVJqLyk&index=2).
He mentions that self
is implied and that you don't have to use it, however my teacher was teaching us that you always need to include self.
Would it still work without self or is it required?
Furthermore, he says it can be called whatever you want, but I have never seen anyone use other names.
class MathematicalQuizApp(tk.Tk):
def __init__(self, *args, *kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
##other code after to make it work that also uses self
Do you have to pass self in the __init__
method or is it implied, meaning you don't have to include it?
What would the actual point of not including it if possible be?
Upvotes: 1
Views: 73
Reputation: 6246
Haven't seen the video link, but i suspect what the video meant by "self is implied and that you don't have to use it" is that you don't need to use the self inside the init block, but it is implied that the init will be passed to the init as the first argument.
In essence, regardless of how you want to read into the video, your teacher is right. methods in a class will get a reference to the object in the first parameter, (which usually is named as self, but you can even change the name to anything. self is not a special keyword).
Whether you use it inside the init method or not has no bearing on the fact that your first argument is going to be a reference to the object.
Upvotes: 1
Reputation: 6154
You are mixing up two things: self
is implied when the constructor (the __init__
method) is called. (The same holds true for every other istance method.) That means, you do not have to (and actually: you cannnot) pass it when you create an instance, and simply write: my_app = MathematicalQuizApp()
(without passing the parameter self
).
In the definition of the constructor (and of any instace method), the very first parameter is implicitly taken as the instance itself, hence the name. If you miss to add a parameter representing the instance in any instance method, Python will take the first parameter you have in the definition of the method as the instance. This will most probably lead to an exception.
You could use any other variable name for the parameter self
. The name self
is just conventional. (But there is no reason not to use it, and many reasons to stick to the convention.)
Upvotes: 0