-->

Python magic method __init__

By: Varghese Chacko 3 years, 3 months ago

Python comes with magic methods that starts its name with __ . The most common one is __init__. What is so magical about __init__? The __init__ method need not be called or invoked. It get invoked/called whenever a class is instantiated. This method is used to initialize the instance. For example, when we run x = A(), the __init__ is invoked. Let us look at the example.

class Bike(object):
    """Blueprint for Bike"""

    def __init__(self, model, color, company, speed_limit):
        self.color = color
        self.company = company
        self.speed_limit = speed_limit
        self.model = model

    def start(self):
        print("started")

    def stop(self):
        print("stopped")

Now let us crate a bike

my_bike = Bike('Honda XYZ', 'Black', 'Honda', '210')

We have created our bike with few arguments 'Honda XYZ', 'Black', 'Honda', '210' and the data is passed to the __init__ of the class Bike. Here the self is the current instance of the class and we are setting the attributes of the instance.

In case we wish to inherit this class and create an new class, say Suzuki, we can reuse the __init__ method of the base class. For example

class Suzuki(Bike):
    """Class for Suzuki bikes."""
    def __init(self, model, color, speed_limit):
        super(Suzuki, self).__init(model, color, sped, 'Suzuki', speed_limit)

Now we can create a suzuki bike as

suzuki_bike = Bike('Honda XYZ', 'Black', '210')

Here we created a class Suzuki for Suzuki bikes and use the __init__ of the class Bike for initializing. Note that we skipped the argument company from constructor so that every bile created using Suzuki will be of Suzuki.

Note: __init__ should not return anything.

Let us talk!

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.