Homepage Forums Dev & Debugging Still confused on __init__

  • Still confused on __init__

     Della Klein updated 4 months, 2 weeks ago 2 Members · 3 Posts
  • Della Klein

    Member
    March 9, 2021 at 6:20 pm
    17 Coins
    0 Gems
    Level: Rookie

    class Character:

    def __init__(self, name):

    self.name = name

    I am still confused on this __init__ thing. I get that it's used in OOP but that's it. Can anyone help me understand this in simple terms?
  • Ryan Brook

    Member
    March 9, 2021 at 7:28 pm
    13 Coins
    0 Gems
    Level: Rookie
    Helpful
    Up
    0
    Down
    Not Helpful

    __init__ does the work of similar to what constructor does in Java/C++.

    Now, let’s understand what constructor is. Constructors are used to initialize the object’s state. The work of a constructor is to assign values to data members of a class when object of class is created. Constructors contain bunch of statements or instructions which are carried away when an object is created. It is run as soon as an object of a class is instantiated.

    class Character:

    def __init__(self, name):

    self.name = name

    def say_hi(self):

    print('Hello, my name is', self.name)

    p = Character('Joe')

    p.say_hi()

    In the above example, a character name Joe is created. While creating a character, “Joe” is passed as an argument, this argument will be passed to the __init__ method to initialize the object. The keyword self represents the instance of a class and binds the attributes with the given arguments. Similarly, many objects of Character class can be created by passing different names as arguments.

  • Della Klein

    Member
    March 14, 2021 at 11:58 pm
    17 Coins
    0 Gems
    Level: Rookie
    Helpful
    Up
    0
    Down
    Not Helpful

    @gaetano85 thanks a lot for this. Much appreciated.

Log in to reply.

Original Post
0 of 0 posts June 2018
Now

New Report

Close