Init in Python

Introduction

In Python, one of the popular methods is __init__. It is referred to as a function Object() { [native code] } in object-oriented programming. When an object is generated from the class and access is necessary to initialise the class's attributes, it is called __init__ function.

Here are several prerequisites that must be met:

  • A class is similar to a blueprint in that variables/attributes and functions/methods are declared. To use the class, we must first build objects for it.
  • We can call the procedures in the class and retrieve the declared attributes using the objects.
  • Every object can have its own values for the class's attributes. When we create the object, we can pass the values we desire as parameters.

What _init_ can do?

  • Every object could have its own values for a class's attributes. The __init__ method can be used to implement this functionality.
  • It is a function Object() { [native code] } that allows a class to hold objects with varying values.
  • It is not necessary to refer to it as a normal procedure. It is analogous to a method within a class. It is called whenever a new object for the class is generated.

Now consider the preceding example with the __init__ method:

The goal is to create a racing game in Python called "NFS."

Solution: If you want to make a racing game in Python called "NFS," one of the first things you'll need to do is generate different cars. Each of the automobiles you design in the game will have unique characteristics such as colour, speed, and other ways such as changing gear, accelerating, breaking, and so on.

Code Implementation

This concept should appear like this when coded into the Python interpreter.

class Car(object):
    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")
    def accelarate(self):
        print("accelarating...")
        # accelarator functionality here
    def change_gear(self, gear_type):
        print("gear changed")
        # gear related functionality here
# Now that we have created the objects, let's move on to create the individual   cars in the game
maruti_suzuki = Car("ertiga", "black", "suzuki", 60)
audi = Car("A6", "red", "audi", 80)

In the preceding example, we constructed two distinct car models: the Suzuki Ertiga and the Audi A6. After successfully creating these objects, we can utilise the __init__ method to initialise them and therefore prepare for the next steps.

In this example, we can also use the self method to represent the various instances of the class and tie the attributes to the given inputs. Using the self method, we will be able to access the properties and methods that we have defined within the class.

Note:

  • Within a class, we can build an unlimited number of objects, attributes, and functions. However, a class can only have one explicit __init__ function.
  • Even if we create many __init__ methods, the most recent one will overwrite the prior ones.

Example

The goal is to calculate the development cost of a rectangular field with the parameters width (b=120) and length (l=160). The price of one square metre is 2000 INR.

Solution: Using the instructions from the previous example as a guide, write the code for this example as follows.

class Rectangle:
    def __init__(self, length, breadth, unit_cost=0):
        self.length = length
        self.breadth = breadth
        self.unit_cost = unit_cost
    def get_perimeter(self):
        return 2 * (self.length + self.breadth)
    def get_area(self):
        return self.length * self.breadth
    def calculate_cost(self):
        area = self.get_area()
        return area * self.unit_cost
# breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % (r.get_area()))
print("Cost of rectangular field: Rs. %s " %(r.calculate_cost()))



>>> Area of Rectangle: 19200 cm^2

    Cost of rectangular field: Rs. 38400000 

write your code here: Coding Playground

As previously explained, the self method reflects the class's instances and characteristics. If you look closely, you will notice that we utilised the methods self.length to calculate the value of the attribute length. The attribute length is already bound within the class, and we are representing the object within the same class via the self function.

In the preceding code, we also used the method def get area(self): as a parameter. This means that every time we call the method, the first parameter is automatically passed together with the other arguments in the method. Although this automation may appear little at first glance, it will save a significant amount of time and boost efficiency in the long term.

Conclusion

In this article, we have covered what is _init_ function and its application. Hope you find this article useful!