Search code examples
pythonobjectselfextending

Reason for self when extending objects (Python)


So say I am extending an object called Frame (found in 'tkinter'), as shown below,

class GraphRegion(Frame):

    def __init__(self, master):
        Frame.__init__(self,master)

Now, I know why 'master' is needed. Why does Frame.__init__ need 'self'? Doesn't 'self' point to GraphRegion? What is this actually telling the object 'Frame'? Is it to create GraphRegion as a type 'Frame'?


Solution

  • Although Martjin's answer is great, I'm going to expand on it, in some, let's say, "lower level" terms.

    Basically, whenever you create a new GraphRegion object (myobject = GraphRegion(master)), __init__ is called with the new object as the first parameter (self), and the master argument as the second parameter.

    Basically, if you do this:

    myobject = GraphRegion(master)
    

    __init__ get's called like this:

    __init__(myobject, master)
    

    This is because you often want to assign properties to specific instances of an object, and self lets you do that. For example, if I had a class Movie, where each instance of it had it's own title, I would use self like this:

    class Movie(object):
        def __init__(self, title):
            self.title = title
    

    That way, every instance of Movie can have it's own title.

    Now, whenever you run Frame.__init__(self, master), that __init__ function often needs to modify the specific instance of the GraphRegion class you're creating (the object you're creating), and self is that instance, so you pass it to the __init__ method.