- Constructors in Python
- Python3
- Python3
- Example:
- Python
- Explanation:
- Advantages of using constructors in Python:
- Disadvantages of using constructors in Python:
- Работа с конструкторами в Python
- Создание конструктора на Python
- Подсчет количества объектов класса
- Непараметрический
- Параметризованный конструктор Python
- Конструктор Python по умолчанию
- Более одного конструктора в одном классе
- Встроенные функции классов Python
- Встроенные атрибуты класса
Constructors in 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 :
def __init__(self): # body of the constructor
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
print ( «First number line number13 index12 alt2″> print ( «Second number line number14 index13 alt1″> print ( «Addition of two numbers line number15 index14 alt2″>
First number = 1000 Second number = 2000 Addition of two numbers = 3000 First number = 10 Second number = 20 Addition of two numbers = 30
Example:
Python
Default constructor called Method called without a name ('Parameterized constructor called with name', 'John') ('Method called with name', 'John')
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
Конструктор в Python – это особый тип метода (функции), который используется для инициализации членов экземпляра класса.
В C ++ или Java конструктор имеет то же имя, что и его класс, в Python конструктор обрабатывается по-разному. Он используется для создания объекта.
Конструкторы бывают двух типов:
Определение конструктора выполняется, когда мы создаем объект этого класса. Конструкторы также проверяют, что у объекта достаточно ресурсов для выполнения любой задачи запуска.
Создание конструктора на Python
В Python метод __init __() имитирует конструктор класса. Этот метод вызывается при создании экземпляра класса. Он принимает ключевое слово self в качестве первого аргумента, который позволяет получить доступ к атрибутам или методу класса.
Мы можем передать любое количество аргументов во время создания объекта класса, в зависимости от определения __init __(). В основном он используется для инициализации атрибутов класса. У каждого класса должен быть конструктор, даже если он просто полагается на конструктор по умолчанию.
Рассмотрим следующий пример для инициализации атрибутов класса Employee при работе с конструкторами в Python.
class Employee: def __init__(self, name, id): self.id = id self.name = name def display(self): print("ID: %d nName: %s" % (self.id, self.name)) emp1 = Employee("John", 101) emp2 = Employee("David", 102) # accessing display() method to print employee 1 information emp1.display() # accessing display() method to print employee 2 information emp2.display()
ID: 101 Name: John ID: 102 Name: David
Подсчет количества объектов класса
Конструктор вызывается автоматически, когда мы создаем объект класса. Рассмотрим следующий пример.
class Student: count = 0 def __init__(self): Student.count = Student.count + 1 s1=Student() s2=Student() s3=Student() print("The number of students:",Student.count)
Непараметрический
Непараметрический конструктор используется, когда мы не хотим манипулировать значением, или конструктором, который имеет только self в качестве аргумента. Разберем на примере.
class Student: # Constructor - non parameterized def __init__(self): print("This is non parametrized constructor") def show(self,name): print("Hello",name) student = Student() student.show("John")
Параметризованный конструктор Python
У параметризованного конструктора есть несколько параметров вместе с самим собой.
class Student: # Constructor - parameterized def __init__(self, name): print("This is parametrized constructor") self.name = name def show(self): print("Hello",self.name) student = Student("John") student.show()
This is parametrized constructor Hello John
Конструктор Python по умолчанию
Когда мы не включаем конструктор в класс или забываем его объявить, он становится конструктором по умолчанию. Он не выполняет никаких задач, а инициализирует объекты. Рассмотрим пример.
class Student: roll_num = 101 name = "Joseph" def display(self): print(self.roll_num,self.name) st = Student() st.display()
Более одного конструктора в одном классе
Давайте посмотрим на другой сценарий, что произойдет, если мы объявим два одинаковых конструктора в классе.
class Student: def __init__(self): print("The First Constructor") def __init__(self): print("The second contructor") st = Student()
В приведенном выше коде объект st вызвал второй конструктор, тогда как оба имеют одинаковую конфигурацию. Первый метод недоступен для объекта st. Внутренне объект класса всегда будет вызывать последний конструктор, если у класса есть несколько конструкторов.
Примечание. Перегрузка конструктора в Python запрещена.
Встроенные функции классов Python
Встроенные функции, определенные в классе, описаны в следующей таблице.
SN | Функция | Описание |
---|---|---|
1 | getattr(obj,name,default) | Используется для доступа к атрибуту объекта. |
2 | setattr(obj, name,value) | Она используется для установки определенного значения для определенного атрибута объекта. |
3 | delattr (obj, name) | Необходима для удаления определенного атрибута. |
4 | hasattr (obj, name) | Возвращает истину, если объект содержит определенный атрибут. |
class Student: def __init__(self, name, id, age): self.name = name self.id = id self.age = age # creates the object of the class Student s = Student("John", 101, 22) # prints the attribute name of the object s print(getattr(s, 'name')) # reset the value of attribute age to 23 setattr(s, "age", 23) # prints the modified value of age print(getattr(s, 'age')) # prints true if the student contains the attribute with name id print(hasattr(s, 'id')) # deletes the attribute age delattr(s, 'age') # this will give an error since the attribute age has been deleted print(s.age)
John 23 True AttributeError: 'Student' object has no attribute 'age'
Встроенные атрибуты класса
Наряду с другими атрибутами класс Python также содержит некоторые встроенные атрибуты класса, которые предоставляют информацию о классе.
Встроенные атрибуты класса приведены в таблице ниже.
SN | Атрибут | Описание |
---|---|---|
1 | __dict__ | Предоставляет словарь, содержащий информацию о пространстве имен класса. |
2 | __doc__ | Содержит строку с документацией класса. |
3 | __name__ | Используется для доступа к имени класса. |
4 | __module__ | Он используется для доступа к модулю, в котором определен этот класс. |
5 | __bases__ | Содержит кортеж, включающий все базовые классы. |
class Student: def __init__(self,name,id,age): self.name = name; self.id = id; self.age = age def display_details(self): print("Name:%s, ID:%d, age:%d"%(self.name,self.id)) s = Student("John",101,22) print(s.__doc__) print(s.__dict__) print(s.__module__)