-2

I just finished my first semester of CIS classes. One class used python to explain Object Oriented Programming and Tkinter for GUI. I noticed that pretty much every line in a python class started with the line "self". Can anyone explain what this means? Here is some code from part of a class project to show what I mean.

from tkinter import * #import everything
from tkinter import ttk

class startFish():
    def __init__(self):
        SIZE = 80

        #create window and set title
        self.mainWindow = Tk()
        self.mainWindow.title('GUI-Practice')
        self.mainWindow.geometry('500x250')       

        titleLabel = Label(self.mainWindow, text="How would you like the list of fish sorted?")
        titleLabel.pack()

        self.var = IntVar()
        R1 = Radiobutton(self.mainWindow, text="Alphabetical", variable = self.var, value = 1)
        R1.pack(side=LEFT, anchor=N)
        R2 = Radiobutton(self.mainWindow, text="Reverse Alphabetical", variable = self.var, value = 2)
        R2.pack(side=LEFT, anchor=N)

        self.testLabel = Label(self.mainWindow, text="Hellos")
        self.testLabel.pack(side=RIGHT)

        self.forwardButton = Button(self.mainWindow, text="Select", command=self.fowardButton_Click).pack(side=LEFT)
        self.exitButton = Button(self.mainWindow, text="Exit", command=self.mainWindow.destroy).pack(side=LEFT)


    def fowardButton_Click(self):
        radioVal= self.var.get()
        self.testLabel.configure(text=radioVal)

        self.mainWindow.mainloop()
The_Redhawk
  • 214
  • 1
  • 2
  • 11

3 Answers3

0

'self' represent the class instance itself but it is an artifact you can call it as you like it can be 'mama' if you want but it is name "self" to help the dev remember that this is the instance itself.

0

When you have an object, and you call a method on that object with this syntax:

my_object.forwardButton_Click()

Python arranges things so that the forwardButton_Click() function is called with "my_object" as its parameter (even though in the call, it doesn't look like it takes any parameters).

In object oriented programming, the object whose method is being called is often called "self", because the method is referring to the object itself.

Dylan McNamee
  • 1,696
  • 14
  • 16
0

self is represent the current instance which is similar to this in javascript, it is often used to create global variables of current context and many . refer this .