Homepage Forums Dev & Debugging Still confused on __init__ Reply To: Still confused on __init__

  • 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.

New Report

Close