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 self.name = 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.
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:
- Create a blank empty “proto” object, a fresh blank slate. We’ll call it
new_obj
for now. - Looks up the class definition for
class Truck
above. - Does Truck have a
__init__
? CallTruck.__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 thedef __init__
) is self, the second is color. - 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 isnew_obj
, but your function can’t keep track of every name for every possible object created. To simplify things, you just callnew_obj
the nameself
. - Once your
Truck.__init__(self, "red")
exits, Python takes this now configured new_obj and assigns it to yourford
variable so you can use it. - From then on, any time you call a function on ford, like
ford.drive()
, Python will putford
as the first parameter you have namedself
.
What python does is translate every access on an object kind of like this:
ford.drive() ---> Truck.drive(ford)
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")
Thank You
Thank You Sir
Great, let me know if you need more help.