Hey guys
on my quest to learn python I keep coming across:
def __init__
I think I understand it is defining a method called "init" - but what's with all the underscores. Or is it some builtin method of Python?
Sorry - confused
Cheers!
__init__ is the function that is called automatically upon an object's construction:
-
class Test:
-
def __init__(self, num): # called when object is constructed
-
self.value = num
-
-
def getVal(self):
-
return self.value
-
-
obj = Test(5) # Test.__init__ called; sets obj.value to num (5)
-
-
print obj.getVal() # prints "5"
-
The double underscores are used when operator overloading. For example, the above class could be written like this:
-
class Test:
-
def __init__(self, num): # called when object is constructed
-
self.value = num
-
-
def __repr__(self): # called when object is printed
-
return self.value
-
-
obj = Test(5) # Test.__init__ called; sets obj.value to num (5)
-
-
print obj # Test.__repr__ called; prints "5"
-
Does that help?
Edit: Just wanted to add that the double underscores in simple terms mean that the function will get called on a special occasion (operator overloading). For example, __init__ gets called when an object is created, __repr__ gets called when the object gets printed, __del__ gets called when object goes out of scope, and there are many others.
Edit 2: Another thing, __init__ is usually used to set up the object by using the arguements to make variables of the object. For example, let's say you have a rectangle class. You'd want the object to have for instance, width and heigth variables. The __init__ would look like this:
-
class Rect:
-
def __init__(self, width, height):
-
self.width = width
-
self.height = height
-
-
myRect = Rect(5, 7)
-