How does “self” in a class work?

Adding to some of the great explanations in here, because the self argument essentially identifies the instance of a given object, you can pass this instance into other instances as well as a way to establish relationships between objects.

For example:

Class MusicBox():
def __init__(self):

    def play_song(self, song):
        #some code that plays some music

    def stop_music(self):
        #some code that stops music currently playing       


Class Menu():
def __init__(self, app):
        self.app = app
        self.menu_music = song_file.mp3
        self.app.music.play_song(self.menu_music)


Class App():
    def __init__(self):
        self.music = MusicBox()
        self.main_menu = Menu(self)

Here we're creating an object to handle playing and stopping music, a menu object we can use for navigation of our app, and storing both in an App object that essentially acts as an instance of our program. So, if you were to create an instance of Class App, it would create a menu and play some theme music for your menu. We pass the self argument to the instance of Menu so that we can then call a method from the App's MusicBox instance (or any other object instance we create within our App). This helps establish a relationship between the MusicBox and Menu instances as they are both part of the same App instance.

/r/learnpython Thread