what is def __init__?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ateale
    New Member
    • Jun 2007
    • 46

    what is def __init__?

    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!
  • ilikepython
    Recognized Expert Contributor
    • Feb 2007
    • 844

    #2
    Originally posted by ateale
    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:
    [code=python]
    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"
    [/code]
    The double underscores are used when operator overloading. For example, the above class could be written like this:
    [code=python]
    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"
    [/code]
    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:
    [code=python]
    class Rect:
    def __init__(self, width, height):
    self.width = width
    self.height = height

    myRect = Rect(5, 7)
    [/code]

    Comment

    • ateale
      New Member
      • Jun 2007
      • 46

      #3
      thanks ilikepython - it makes sense - will read over that a few more times

      thanks for explaining!

      Comment

      • ilikepython
        Recognized Expert Contributor
        • Feb 2007
        • 844

        #4
        Originally posted by ateale
        thanks ilikepython - it makes sense - will read over that a few more times

        thanks for explaining!
        You're welcome, if you have a question, feel free to ask.

        Comment

        Working...