Какое ключевое слово используется для конструктора python
Перейти к содержимому

Какое ключевое слово используется для конструктора python

  • автор:

# __init__() — метод создания класса

В объектно-ориентированном программировании конструктором класса называют метод, который автоматически вызывается при создании объектов. Его также можно назвать конструктором объектов класса. Имя такого метода обычно регламентируется синтаксисом конкретного языка программирования. В Python же роль конструктора играет метод __init__() .

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

При этом методы перегрузки операторов не надо вызывать по имени. Вызовом для них является сам факт участия объекта в определенной операции. В случае конструктора класса – это операция создания объекта. Так как объект создается в момент вызова класса по имени, то в этот момент вызывается метод __init__() , если он определен в классе.

Необходимость конструкторов связана с тем, что нередко объекты должны иметь собственные свойства сразу. Пусть имеется класс Person, объекты которого обязательно должны иметь имя и фамилию. Если класс будет описан подобным образом:

то создание объекта возможно без полей. Для установки имени и фамилии метод setName() нужно вызывать отдельно:

В свою очередь, конструктор класса не позволит создать объект без обязательных полей:

Здесь при вызове класса в круглых скобках передаются значения, которые будут присвоены параметрам метода __init__() . Первый его параметр – self – ссылка на сам только что созданный объект.

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

В консоль выводиться ошибка: «отсутствует 2 обязательных позиционных аргумента: "n" и "s":

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

Если класс вызывается без значений в скобках, то для параметров будут использованы их значения по умолчанию. Однако поля width и height будут у всех объектов.

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

# __del__() — метод деструктор класса

Помимо конструктора объектов в языках программирования есть обратный ему метод – деструктор. Он вызывается для удаления объекта из памяти.

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

В классах Python функцию деструктора выполняет метод __del__() .

Кроме того, мы можем определить в классе деструктор, реализовав встроенную функцию __del__() , который будет вызываться либо в результате вызова оператора del, либо при автоматическом удалении объекта. Например:

Вывод в консоль:

# Упражнения

Есть класс Person, конструктор которого принимает три параметра (не учитывая self) – имя, фамилию и квалификацию специалиста. Квалификация имеет значение заданное по умолчанию, равное единице.

У класса Person есть метод, который возвращает строку, включающую в себя всю информацию о сотруднике.

Класс Person содержит деструктор, который выводит на экран фразу «До свидания, мистер …» (вместо троеточия должны выводиться имя и фамилия объекта).

В основной ветке программы создайте три объекта класса Person. Посмотрите информацию о сотрудниках и увольте самое слабое звено.

В конце программы добавьте функцию input("Press any key…") , чтобы скрипт не завершился сам, пока не будет нажат Enter. Иначе вы сразу увидите как удаляются все объекты при завершении работы программы.

Какое ключевое слово используется для конструктора python

Prerequisites: Object-Oriented Programming in Python, Object-Oriented Programming in Python | Set 2
Constructors are generally used for instantiating an object. The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created. In Python the __init__() method is called the constructor and is always called when an object is created.
Syntax of constructor declaration :

Types of constructors :

  • default constructor: The default constructor is a simple constructor which doesn’t accept any arguments. Its definition has only one argument which is a reference to the instance being constructed.
  • parameterized constructor: constructor with parameters is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer.

Example of default constructor :

Python3

Example of the parameterized constructor :

Python3

Example:

Python

Explanation:

In this example, we define a class MyClass with both a default constructor and a parameterized constructor. The default constructor checks whether a parameter has been passed in or not, and prints a message to the console accordingly. The parameterized constructor takes in a single parameter name and sets the name attribute of the object to the value of that parameter.

We also define a method method() that checks whether the object has a name attribute or not, and prints a message to the console accordingly.

We create two objects of the class MyClass using both types of constructors. First, we create an object using the default constructor, which prints the message “Default constructor called” to the console. We then call the method() method on this object, which prints the message “Method called without a name” to the console.

Next, we create an object using the parameterized constructor, passing in the name “John”. The constructor is called automatically, and the message “Parameterized constructor called with name John” is printed to the console. We then call the method() method on this object, which prints the message “Method called with name John” to the console.

Overall, this example shows how both types of constructors can be implemented in a single class in Python.

Advantages of using constructors in Python:

  • Initialization of objects: Constructors are used to initialize the objects of a class. They allow you to set default values for attributes or properties, and also allow you to initialize the object with custom data.
  • Easy to implement: Constructors are easy to implement in Python, and can be defined using the __init__() method.
  • Better readability: Constructors improve the readability of the code by making it clear what values are being initialized and how they are being initialized.
  • Encapsulation: Constructors can be used to enforce encapsulation, by ensuring that the object’s attributes are initialized correctly and in a controlled manner.

Disadvantages of using constructors in Python:

  • Overloading not supported: Unlike other object-oriented languages, Python does not support method overloading. This means that you cannot have multiple constructors with different parameters in a single class.
  • Limited functionality: Constructors in Python are limited in their functionality compared to constructors in other programming languages. For example, Python does not have constructors with access modifiers like public, private or protected.
  • Constructors may be unnecessary: In some cases, constructors may not be necessary, as the default values of attributes may be sufficient. In these cases, using a constructor may add unnecessary complexity to the code.

Overall, constructors in Python can be useful for initializing objects and enforcing encapsulation. However, they may not always be necessary and are limited in their functionality compared to constructors in other programming languages.

Классы

Объектно-ориентированное программирование (ООП) — это парадигма программирования, где различные компоненты программы моделируются на основе реальных объектов. Объект — это что-либо, у чего есть какие-либо характеристики и то, что может выполнить какую-либо функцию.

Python — объектно ориентированный язык программирования и почти всё в нём является объектами, имеющими свои свойства и методы. Ранее уже встречались типы данных, которые являются встроенными. Однако также можно определять собственные типы с помощью классов.

Классы могут иметь свои переменные (атрибуты), свои функции (методы), которые определяют новый тип данных и его поведение. Определяется класс с помощью ключевого слова class и синтаксис выглядит следующим образом:

Создадим пустой класс с помощью знакомого оператора pass :

Классический пример с созданием условного человека. Здесь никаких атрибутов или методов явно не определяется, однако уже есть возможность создать экземпляры этого класса (объекты). Создать (инициализировать) объект можно вызвав данный класс как функцию:

Оба созданных объекта имеют один и тот же тип, однако не являются одним и тем же объектом. Проверить последнее утверждение можно с помощью оператора is .

Конструктор

В предыдущем примере может возникнуть вопрос — если не определялось никаких функций/методов, то как было вызвано создание объекта? Ответ — почти все классы неявно наследуются от базового класса object , в котором определён набор специальных методов. Одним из таких методов является __init__() , который и вызывается при создании нового объекта.

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

Доступ к параметрам или методам объекта осуществляется указанием соответствующего названия переменной после точки . .

Заметка

При определении методов класса первый аргумент является ссылкой на текущий экземпляр класса, который используется для доступа к переменным, принадлежащим этому классу. Принято использовать название self для данной переменной.

Атрибуты

Атрибуты можно разделись на два вида:

  • атрибуты класса — являются общими для всех экземпляров класса, объявляются в теле конструкции class вне любого метода.
  • атрибуты экземпляров — являются собственностью экземпляра класса, объявляются обычно внутри любого метода.

В указанном примере мы создаем класс Person с двумя атрибутами класса species и count , а также двумя атрибутами экземпляра name и age . Класс содержит один специальный метод __init__() , который содержит наши два атрибута экземпляров. Значения для атрибутов переданы в качестве аргументов методу __init__() . Внутри метода __init__() атрибут класса count увеличивается на единицу.

Создадим объект класса Person и выведем пару значений:

Как можно видеть, атрибут count имеет значение 1 . Теперь создадим еще один объект класса Person :

Значение атрибута count увеличилось еще на единицу. Как уже говорилось ранее, это связано с тем, что для объекта person_1 и person_2 атрибут класса count является общим.

Методы

Методы используются для реализации функционалов объекта. Создание метода объекта от обычной функции отличается лишь в использовании первого аргумента в качестве ссылки на объект ( self ). Стоит отметить, что если попытаться вызвать метод не от объекта, а от класса, то придется этот первый аргумент передавать вручную, т.е. объект, который не был создан.

Однако, есть тип методов, который может быть вызван напрямую при помощи имени класса. Такие методы называются статичными методами и указываются с помощью декоратора @staticmethod перед созданием метода:

Как видите, нам не нужно создавать экземпляр класса Person , чтобы вызвать метод get_details() . Для этого достаточно использовать название класса.

Заметка

Статические методы могут иметь доступ только к атрибутам класса, т.е. обратиться к методам и атрибутам с помощью self нельзя.

Модификаторы доступа

Модификаторы доступа в Python используются для модификации области видимости переменных по умолчанию. Есть три типа модификаторов доступов в Python ООП:

  • публичный (public) — доступ открыт из любого места вне класса;
  • защищенный (protected) — доступ открыт только внутри того же пакета, создается с добавлением к названию переменной одного нижнего подчеркивания _ в начале;
  • приватный (private) — доступ открыт только внутри класса, создается с добавлением к названию переменной двойного нижнего подчеркивания __ в начале.

Довольно неожиданный результат, сработало только по логике правильно только два модификатора — публичный и приватный. На деле можно получить и значение приватной переменной следующим образом:

Это указывает на то, что в Python нету явных модификаторов доступа. Данная тема до сих пор вызывает у многих вопросы. Некоторые считают это большим минусов в ООП Python, другие наоборот плюсом. Можно сослаться на фразу из философии дизайна Python — “Явное лучше чем неявное”. На деле, если при разработке в классе встречается переменная с подчеркиванием в начале названия, т.е. модификатором, то стоит дважды подумать, стоит ли ее изменять или же это сломает логику работы класса, которую в нее заложил разработчик.

Подсказка

Почитать философию дизайна Python можно импортировав модуль this в REPL:

Наследование

Наследование в объектно-ориентированном программировании очень похоже на наследование в реальной жизни, где ребенок наследует те или иные характеристики его родителей в дополнение к его собственным характеристикам.

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

Выше мы создаем два класса: Person и Student , который наследует класс Person . Чтобы наследовать класс, вам нужно только вписать название родительского класса внутри скобок, которая следует за названием дочернего класса. Класс Person содержит метод person_method() , а дочерний класс содержит метод student_method() . Однако, так как класс Student наследует класс Person , он также наследует и метод person_method() :

Также в Python поддерживается множественное наследование. Родительский класс может иметь несколько дочерних, и, аналогично, дочерний класс может иметь несколько родительских классов.

Пример наследования по цепочке:

Пример наследования от нескольких классов:

Полиморфизм

Термин полиморфизм буквально означает наличие нескольких форм. В контексте объектно-ориентированного программирования, полиморфизм означает способность объекта вести себя по-разному. Полиморфизм в программировании реализуется через перегрузку метода, либо через его переопределение.

Перегрузка метода относится к свойству метода вести себя по-разному, в зависимости от количества или типа параметров. Пример:

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

Инкапсуляция

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

Чтобы предоставить контролируемый доступ к данным класса в Python, используются модификаторы доступа и свойства. Мы уже ознакомились с тем, как действуют модификаторы доступа. В этом разделе мы посмотрим, как действуют свойства.

Предположим, что нам нужно убедиться в том, что модель автомобиля должна датироваться между 2000 и 2018 годом. Если пользователь пытается ввести значение меньше 2000 для модели автомобиля, значение автоматически установится как 2000, и если было введено значение выше 2018, оно должно установиться на 2018. Если значение находится между 2000 и 2018 — оно остается неизменным. Мы можем создать свойство атрибута модели, которое реализует эту логику. Взглянем на пример:

Constructors in Python

Constructor is a special method used to create and initialize an object of a class. On the other hand, a destructor is used to destroy the object.

After reading this article, you will learn:

  • How to create a constructor to initialize an object in Python
  • Different types of constructors
  • Constructor overloading and chaining

Table of contents

What is Constructor in Python?

In object-oriented programming, A constructor is a special method used to create and initialize an object of a class. This method is defined in the class.

  • The constructor is executed automatically at the time of object creation.
  • The primary use of a constructor is to declare and initialize data member/ instance variables of a class. The constructor contains a collection of statements (i.e., instructions) that executes at the time of object creation to initialize the attributes of an object.

For example, when we execute obj = Sample() , Python gets to know that obj is an object of class Sample and calls the constructor of that class to create an object.

Note: In Python, internally, the __new__ is the method that creates the object, and __del__ method is called to destroy the object when the reference count for that object becomes zero.

In Python, Object creation is divided into two parts in Object Creation and Object initialization

  • Internally, the __new__ is the method that creates the object
  • And, using the __init__() method we can implement constructor to initialize the object.

Syntax of a constructor

  • def : The keyword is used to define function.
  • __init__() Method: It is a reserved method. This method gets called as soon as an object of a class is instantiated.
  • self : The first argument self refers to the current object. It binds the instance to the __init__() method. It’s usually named self to follow the naming convention.

Note: The __init__() method arguments are optional. We can define a constructor with any number of arguments.

Example: Create a Constructor in Python

In this example, we’ll create a Class Student with an instance variable student name. we’ll see how to use a constructor to initialize the student name at the time of object creation.

Output

  • In the above example, an object s1 is created using the constructor
  • While creating a Student object name is passed as an argument to the __init__() method to initialize the object.
  • Similarly, various objects of the Student class can be created by passing different names as arguments.

Create object in Python using a constructor

Create an object in Python using a constructor

Note:

  • For every object, the constructor will be executed only once. For example, if we create four objects, the constructor is called four times.
  • In Python, every class has a constructor, but it’s not required to define it explicitly. Defining constructors in class is optional.
  • Python will provide a default constructor if no constructor is defined.

Types of Constructors

In Python, we have the following three types of constructors.

  • Default Constructor
  • Non-parametrized constructor
  • Parameterized constructor

Types of constructor

Types of constructor

Default Constructor

Python will provide a default constructor if no constructor is defined. Python adds a default constructor when we do not include the constructor in the class or forget to declare it. It does not perform any task but initializes the objects. It is an empty constructor without a body.

If you do not implement any constructor in your class or forget to declare it, the Python inserts a default constructor into your code on your behalf. This constructor is known as the default constructor.

It does not perform any task but initializes the objects. It is an empty constructor without a body.

Note:

  • The default constructor is not present in the source py file. It is inserted into the code during compilation if not exists. See the below image.
  • If you implement your constructor, then the default constructor will not be added.

Example:

Output

As you can see in the example, we do not have a constructor, but we can still create an object for the class because Python added the default constructor during a program compilation.

Non-Parametrized Constructor

A constructor without any arguments is called a non-parameterized constructor. This type of constructor is used to initialize each object with default values.

This constructor doesn’t accept the arguments during object creation. Instead, it initializes every object with the same set of values.

Output

As you can see in the example, we do not send any argument to a constructor while creating an object.

Parameterized Constructor

A constructor with defined parameters or arguments is called a parameterized constructor. We can pass different values to each object at the time of creation using a parameterized constructor.

The first parameter to constructor is self that is a reference to the being constructed, and the rest of the arguments are provided by the programmer. A parameterized constructor can have any number of arguments.

For example, consider a company that contains thousands of employees. In this case, while creating each employee object, we need to pass a different name, age, and salary. In such cases, use the parameterized constructor.

Example:

Output

In the above example, we define a parameterized constructor which takes three parameters.

Constructor With Default Values

Python allows us to define a constructor with default values. The default value will be used if we do not pass arguments to the constructor at the time of object creation.

The following example shows how to use the default values with the constructor.

Example

Output

As you can see, we didn’t pass the age and classroom value at the time of object creation, so default values are used.

Self Keyword in Python

As you all know, the class contains instance variables and methods. Whenever we define instance methods for a class, we use self as the first parameter. Using self , we can access the instance variable and instance method of the object.

The first argument self refers to the current object.

Whenever we call an instance method through an object, the Python compiler implicitly passes object reference as the first argument commonly known as self.

It is not mandatory to name the first parameter as a self . We can give any name whatever we like, but it has to be the first parameter of an instance method.

Example

Output

Constructor Overloading

Constructor overloading is a concept of having more than one constructor with a different parameters list in such a way so that each constructor can perform different tasks.

For example, we can create a three constructor which accepts a different set of parameters

Python does not support constructor overloading. If we define multiple constructors then, the interpreter will considers only the last constructor and throws an error if the sequence of the arguments doesn’t match as per the last constructor. The following example shows the same.

Example

Output

  • As you can see in the above example, we defined multiple constructors with different arguments.
  • At the time of object creation, the interpreter executed the second constructor because Python always considers the last constructor.
  • Internally, the object of the class will always call the last constructor, even if the class has multiple constructors.
  • In the example when we called a constructor only with one argument, we got a type error.

Constructor Chaining

Constructors are used for instantiating an object. The task of the constructor is to assign value to data members when an object of the class is created.

Constructor chaining is the process of calling one constructor from another constructor. Constructor chaining is useful when you want to invoke multiple constructors, one after another, by initializing only one instance.

In Python, constructor chaining is convenient when we are dealing with inheritance. When an instance of a child class is initialized, the constructors of all the parent classes are first invoked and then, in the end, the constructor of the child class is invoked.

Using the super() method we can invoke the parent class constructor from a child class.

Example

Output

Counting the Number of objects of a Class

The constructor executes when we create the object of the class. For every object, the constructor is called only once. So for counting the number of objects of a class, we can add a counter in the constructor, which increments by one after each object creation.

Example

Output

Constructor Return Value

In Python, the constructor does not return any value. Therefore, while declaring a constructor, we don’t have anything like return type. Instead, a constructor is implicitly called at the time of object instantiation. Thus, it has the sole purpose of initializing the instance variables.

The __init__() is required to return None. We can not return something else. If we try to return a non-None value from the __init__() method, it will raise TypeError.

Example

Output

Conclusion and Quick recap

In this lesson, we learned constructors and used them in object-oriented programming to design classes and create objects.

The below list contains the summary of the concepts we learned in this tutorial.

  • A constructor is a unique method used to initialize an object of the class.
  • Python will provide a default constructor if no constructor is defined.
  • Constructor is not a method and doesn’t return anything. it returns None
  • In Python, we have three types of constructor default, Non-parametrized, and parameterized constructor.
  • Using self, we can access the instance variable and instance method of the object. The first argument self refers to the current object.
  • Constructor overloading is not possible in Python.
  • If the parent class doesn’t have a default constructor, then the compiler would not insert a default constructor in the child class.
  • A child class constructor can also invoke the parent class constructor using the super() method.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

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

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