Перейти к содержимому

Как много конструкторов в классе может иметь python

  • автор:

Overload a Constructor in Python

Overload a Constructor in Python

Multiple constructors help in customizing our custom class accordingly to its parameters. While using different parameters, we can trigger different constructors.

Multiple constructors are not directly supported in Python. When multiple constructors are provided in the class, the latest one overrides the previous one. But there are some alternative ways to overload a constructor in Python.

We will discuss these methods in this article.

Using Multiple Arguments to Overload Constructors in Python

Function overloading refers to having different functions with the same name with different types of parameters. We can overload a constructor by declaring multiple conditions, with every condition based on a different set of arguments.

In the above example, we have two types of parameters in the constructor. One is a string, and the other is an integer. The construct is overloaded to give the output based on the type of arguments provided.

We can also overload a constructor based on the number of arguments provided. This method is similar to the previous example.

See the code below.

Use the @classmethod Decorators to Overload a Constructor in Python

The @classmethod decorator allows the function to be accessible without instantiating a class. Such methods can be accessed by the class itself and via its instances. When used in overloading, such functions are called factory methods. We can use them to implement the concept of constructor overloading in Python.

See the code below.

This method is the most pythonic way of overloading a constructor. In the above example, the cls argument of the factory method refers to the class itself.

What is a clean, Pythonic way to have multiple constructors in Python?

Python does not support explicit multiple constructors, yet there are some ways using which multiple constructors can be achieved. If multiple __init__ methods are written for the same class, then the latest one overwrites all the previous constructors and the reason for this can be, python stores all the function names in a class as key in a dictionary so, when a new function is defined with the same name, the key remains the same but the value gets overridden by the new function body.

Look at the example below.

Python3

Need for multiple constructors

Multiple constructors are required when one has to perform different actions on the instantiation of a class. This is useful when the class has to perform different actions on different parameters. The class constructors can be made to exhibit polymorphism in three ways which are listed below.

  1. Overloading constructors based on arguments.
  2. Calling methods from __init__.
  3. Using @classmethod decorator.

This article explains how to have multiple constructors in a clean and Pythonic way with examples.

Overloading constructors based on arguments

The constructor overloading is done by checking conditions for the arguments passed and performing required actions. For example, consider passing an argument to the class sample,

  • If the parameter is an int, the square of the number should be the answer.
  • If the parameter is a String, the answer should be “Hello!!”+string.
  • If the parameter is of length greater than 1, the sum of arguments should be stored as the answer.

Python3

In the code above, the instance variable was ans, but its values differ based on the arguments. Since a variable number of arguments for the class, *args is used which is a tuple that contains the arguments passed and can be accessed using an index. In the case of int and string, only one argument is passed and thus accessed as args[0] (the only element in the tuple).

Calling methods from __init__

A class can have one constructor __init__ which can perform any action when the instance of the class is created. This constructor can be made to different functions that carry out different actions based on the arguments passed. Now consider an example :

  • If the number of arguments passed is 2, then evaluate the expression x = a 2 -b 2
  • If the number of arguments passed is 3, then evaluate the expression y = a 2 +b 2 -c.
  • If more than 3 arguments have been passed, then sum up the squares, divide it by thehighest value in the arguments passed.

Python3

In the example above, the equation to be evaluated is written on different instance methods and made to return the answer. The constructor calls the appropriate method and acts differently for different parameters.

The expressions have been evaluated as follows:

inputs : 1,2 —> 1 2 -2 2 = 1-4 = -3

inputs : 1,2,3 —> (1 2 + 2 2 ) – 3 = 5-3 = 2

inputs : 1,2,3,4,5 —> (1 2 + 2 2 + 3 2 + 4 2 + 5 2 ) / 5 = 55/5 = 11.0

Using @classmethod decorator

This decorator allows a function to be accessible without instantiating the class. The functions can be accessed both by the instance of the class and the class itself. The first parameter of the method that is declared as classmethod is cls, which is like the self of the instance methods. Here cls refer to the class itself. This proves to be very helpful to use multiple constructors in Python and is a more Pythonic approach considered to the above ones. Consider the same example used above. Evaluate different expressions based on the number of inputs.

Несколько конструкторов с разным количеством аргументов

Можно ли в Python в одном классе делать несколько конструкторов с разным количеством аргументов?

В данном случае можно создавать экземпляры класса только со вторым констуктором, в то время как запись x = a(42) вызовет ошибку.

Nicolas Chabanovsky's user avatar

Если быть кратким то НЕТ.

Более детально посмотрите обсуждение вот ЗДЕСЬ. Там и варианты решений есть такие как использование необязательных или ключевых аргументов.

y_v's user avatar

В Python’е перегрузок функций (а конструктор, по факту — это функция) нет в принципе. В вашем случае, вызывается всегда второй конструктор, ибо инструкция def означает «создать объект функции и присвоить этот объект написанному имени», то есть, сначала вы присваиваете имени __init__ одну функцию (с параметром b ), а затем — тому же имени — другую функцию, уже без параметра b .

Поведение, которого вы добиваетесь, можно получить, используя параметры по умолчанию, например:

а не проще сделать так:

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.9.7.43618

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

#18 – Конструкторы, переопределение методов

Конструкторы позволяют задать некие характеристики для объекта сразу же при его создании. К примеру, у вас есть несколько переменных, которые точно должен иметь объект. Вы можете создать конструктор и указать несколько параметров, которые будут переданы при создании объекта.

В одном классе может быть неограниченное количество конструкторов и сам интерпретатор будет понимать к какому конструктору вы обращаетесь. Чтобы создать конструктор необходимо использовать ключевое слово __init__ .

Пример класса с конструктором:

Задание к уроку

Необходимо оформить подписку на проект, чтобы получить доступ ко всем домашним заданиям

Большое задание по курсу

Вам необходимо оформить подписку на сайте, чтобы иметь доступ ко всем большим заданиям. В задание входит методика решения, а также готовый проект с ответом к заданию.
PS: подобные задания доступны при подписке от 1 месяца

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *