Inti function in classes

Why do we use init function and why do we use self inside the parameters of init function?

init is a special marker, that python sees and knows that when the class is initiated you want something specific to happen. You can make a class without one if you want. The = name, say … in that init is telling python,. I want this class to own an attribute-name… it belongs to it’self’ and it is that passed thing, name. Hope that’s helpful.

1 Like

Imagine you have this code:

class Truck(object):
    def __init__(self, color):
        self.color = color

ford = Truck("red")

When you do ford = Truck("red") you are telling python to make you an instance of Truck and assign it to the variable ford. You are also telling Python to tell the Truck (that you’re calling ford), that its color is red. What Python does then is the following:

  1. Create a blank empty “proto” object, a fresh blank slate. We’ll call it new_obj for now.
  2. Looks up the class definition for class Truck above.
  3. Does Truck have a __init__? Call Truck.__init__ passing in the proto object from #1 as the first parameter, and any other arguments to Truck (in this case “red”) as the remaining objects. That first parameter (look at the def __init__) is self, the second is color.
  4. Your Truck.__init__(new_obj, "red") function call runs, and you get a chance to run any code you want to configure this fresh baby blank slate object to be ready for Truck usage. This is new_obj, but your function can’t keep track of every name for every possible object created. To simplify things, you just call new_obj the name self.
  5. Once your Truck.__init__(self, "red") exits, Python takes this now configured new_obj and assigns it to your ford variable so you can use it.
  6. From then on, any time you call a function on ford, like, Python will put ford as the first parameter you have named self.

What python does is translate every access on an object kind of like this: --->
ford.driveto("Kansas") --> Truck.driveto(ford, "Kansas")

What the __init__ is solving is the problem that there is no def Truck() that you can call at the beginning of an object’s creation. You only have class Truck(object) which isn’t a function. So, to make the code ford = Truck("red") work, Python needs some first function to call to setup the new object. That function is __init__, so using the translation I just gave you it’s also kind of like this:

ford = Truck("red") --->  Truck.__init__(ford, "red")
1 Like

Thank You :slight_smile:

Thank You Sir :slightly_smiling_face:

Great, let me know if you need more help.