What is def init self python

Python Class Constructor – Python __init__() Function

Python class constructor function job is to initialize the instance of the class. Python __init__() is the constructor function for the classes in Python.

Python __init__() Function Syntax

The __init__() function syntax is:

def __init__(self, [arguments])
  • The def keyword is used to define it because it’s a function.
  • The first argument refers to the current object. It binds the instance to the init() method. It’s usually named “self” to follow the naming convention. You can read more about it at Python self variable.
  • The init() method arguments are optional. We can define a constructor with any number of arguments.

Python Class Constructor Examples

Let’s look at some examples of the constructor function in different scenarios.

1. Class with No Constructor

We can create a class without any constructor definition. In this case, the superclass constructor is called to initialize the instance of the class. The object class is the base of all the classes in Python.

class Data: pass d = Data() print(type(d)) #

Читайте также:  Python комплексные числа сложение

Here is another example to confirm that the superclass constructor is called to initialize the instance of the subclass.

class BaseData: def __init__(self, i): print(f'BaseData Constructor with argument ') self.id = i class Data(BaseData): pass d = Data(10) print(type(d))

BaseData Constructor with argument 10

2. Simple Constructor with No-Arguments

We can create a constructor without any arguments. It’s useful for logging purposes such as keeping a count of the instances of the class.

class Data1: count = 0 def __init__(self): print('Data1 Constructor') Data1.count += 1 d1 = Data1() d2 = Data1() print("Data1 Object Count =", Data1.count)
Data1 Constructor Data1 Constructor Data1 Object Count = 2

3. Class Constructor with Arguments

Most of the time, you will find the constructor function with some arguments. These arguments are generally used to initialize the instance variables.

class Data2: def __init__(self, i, n): print('Data2 Constructor') self.id = i self.name = n d2 = Data2(10, 'Secret') print(f'Data ID is and Name is ')
Data2 Constructor Data ID is 10 and Name is Secret

4. Class Constructor with Inheritance

class Person: def __init__(self, n): print('Person Constructor') self.name = n class Employee(Person): def __init__(self, i, n): print('Employee Constructor') super().__init__(n) # same as Person.__init__(self, n) self.id = i emp = Employee(99, 'Pankaj') print(f'Employee ID is and Name is ')
Employee Constructor Person Constructor Employee ID is 99 and Name is Pankaj
  • It is our responsibility to call the superclass constructor.
  • We can use the super() function to call the superclass constructor function.
  • We can also use the superclass name to call its init() method.

5. Constructor Chaining with Multilevel Inheritance

class A: def __init__(self, a): print('A Constructor') self.var_a = a class B(A): def __init__(self, a, b): super().__init__(a) print('B Constructor') self.var_b = b class C(B): def __init__(self, a, b, c): super().__init__(a, b) print('C Constructor') self.var_c = c c_obj = C(1, 2, 3) print(f'c_obj var_a=, var_b=, var_c=')
A Constructor B Constructor C Constructor c_obj var_a=1, var_b=2, var_c=3

6. Constructor with Multiple Inheritance

We can’t use super() to access all the superclasses in case of multiple inheritances. The better approach would be to call the constructor function of the superclasses using their class name.

class A1: def __init__(self, a1): print('A1 Constructor') self.var_a1 = a1 class B1: def __init__(self, b1): print('B1 Constructor') self.var_b1 = b1 class C1(A1, B1): def __init__(self, a1, b1, c1): print('C1 Constructor') A1.__init__(self, a1) B1.__init__(self, b1) self.var_c1 = c1 c_obj = C1(1, 2, 3) print(f'c_obj var_a=, var_b=, var_c=')
C1 Constructor A1 Constructor B1 Constructor c_obj var_a=1, var_b=2, var_c=3

Python Doesn’t Support Multiple Constructors

Python doesn’t support multiple constructors, unlike other popular object-oriented programming languages such as Java.

We can define multiple __init__() methods but the last one will override the earlier definitions.

class D: def __init__(self, x): print(f'Constructor 1 with argument ') # this will overwrite the above constructor definition def __init__(self, x, y): print(f'Constructor 1 with arguments , ') d1 = D(10, 20) # Constructor 1 with arguments 10, 20

Can Python __init__() function return something?

If we try to return a non-None value from the __init__() function, it will raise TypeError.

class Data: def __init__(self, i): self.id = i return True d = Data(10)
TypeError: __init__() should return None, not 'bool'

If we change the return statement to return None then the code will work without any exception.

References:

Источник

What is __init__ and self in Python?

Summary: In this tutorial, we will learn what __init__ and self are in Python and when we should use them in our Python program.

What is __init__ in Python?

__init__ is a reserved function in Python that is invoked when an object of a class is created (once per object, similar to the constructors in Java and C++).

It does not return any value and is mainly used to initialize the properties of an object.

For instance, consider the following Python class:

class Car: def __init__(self): print("Building the Car") self.name = "Lamborghini" self.max_speed = "220 mph" def display(self): print(f"Name: ") print(f"Max Speed: ") #creating object of the class myCar = Car() print("-----------------") #calling the display function of the myCar object myCar.display()

Building the Car
—————–
Name: Lamborghini
Max Speed: 220 mph

As we can see, during the creation of the object the __init__ method was automatically invoked. Inside the same, we have initialized the name and max_speed properties of the myCar object and output them into the display function.

Similarly, we can write other statements as well, that we want to execute at the time of the creation of the object.

Tip: Use __init__ function for the initialization of the data members.

__init__ function with Parameters

We can also pass arguments to the __init__ method to initialize data members of different objects with unique values.

For this, we declare parameters in the declaration of the __init__ function and pass the values for the same during the object creation as follows:

class Car: def __init__(self, name, speed): print("Building the Car") self.name = name self.max_speed = speed def display(self): print(f"Name: ") print(f"Max Speed: ") myCar = Car("Maruti", "120 mph") print("-----------------") myCar.display()

Building the Car
—————–
Name: Maruti
Max Speed: 120 mph

It is important to know that the value for self is passed by Python itself, we do not need to pass the value for it.

What is self in Python?

self is a keyword in Python that holds the reference of the current instance of the class.

It is used to access the properties and functions of the current working instance.

Here, the current instance means the object in action.

Python passes the reference of the current instance as the first parameter to the every instance methods of the class including the __init__ function, hence it is important to declare self as the first parameter in those functions to hold the reference of the object.

We have used the self keyword in the previous example to assign and access the values of the data members.

Consider the following code for instance:

class Car: def __init__(): pass def display(): pass myCar = Car() myCar.display()

: __init__() and display() takes 0 positional arguments but 1 was given

It is clear from the error, that Python by default is passing one argument to the __init__ and display methods, but they don’t have any parameter to hold the value.

Let’s catch the value in the self and output it to see what’s being passed:

class Car: def __init__(self): print(self) def display(self): print(self) myCar = Car() myCar.display()

From the output, we can observe that the value of self in both functions are the same instance of the Car class.

Can We Rename self?

Declaring the first parameter in the declaration of every instance method is important, however, it doesn’t have to be only self .

We can name the keyword to whatever we like.

class Car: def __init__(obj): print(obj) def display(car): print(car) myCar = Car() myCar.display()

Adarsh Kumar

I am an engineer by education and writer by passion. I started this blog to share my little programming wisdom with other programmers out there. Hope it helps you.
LinkedIn

Источник

Оцените статью