r/programminghelp • • Feb 05 '20

Python What is the ELI5 of __init__ and self in Python?

4 Upvotes

1 comment sorted by

3

u/marko312 Feb 05 '20

I'm assuming you are wondering about something like

class SomeClass(...):
    def __init__(self, ...):
        # some code

In that case:

When creating a new object (an instance), you oftentimes want to run an additional piece of code - usually to set some values for the instance from any parameters provided.

This is where the special function __init__ comes in - when you create a new instance of a class, __init__ immediately gets called on it (with any parameters provided).

Now, before going into how the parameters are passed, you should know about how "member functions" (functions which are called on an object, such as someObject.someFunction()) work in python. Basically, whenever you use such a function, the function is treated as if it was called with the object as its first parameter:

class SomeClass:
    def someFunction(self):
        print(self)

someObject.someFunction()
# Is translated to
SomeClass.someFunction(someObject)

Because the first argument corresponds to the object the function was called on, it is named self by custom - however, you can use any name for it that you want, just make sure that you don't forget about the extra parameter.

Going back to __init__:

def SomeClass:
    def __init__(self, a):
        # set the "value" for the new object to the parameter passed (a)
        self.value = a

instance = SomeClass(4)
# this works as if "instance" was set to an instance of the class
# and then instance.__init__(4) was called
# (which itself is effectively SomeClass.__init__(instance, 4) )

print(instance.value)
# prints "4"