Python call superclass method

Функция super() в Python — получение унаследованных методов

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

Как вызвать функцию super() в Python3

Чтобы вызвать функцию super() в Python, создайте родительский и дочерний классы, наследуйте родительский класс дочернему классу, а затем вызовите метод super() из дочернего класса.

Как видите, это базовая установка одиночного наследования.

Мы можем видеть базовый или родительский класс(также иногда называемый суперклассом) и производный класс или подкласс, но нам все еще нужно инициализировать родительский или базовый класс в подклассе, производном или дочернем.

Мы можем вызвать функцию super(), чтобы сделать процесс более доступным. Функция super() призвана предоставить гораздо более абстрактное и переносимое решение для инициализации классов.

Пример 1

В приведенном выше примере мы определили один базовый класс — Computer, и производный класс — Laptop.

Мы определили три свойства внутри базового класса; производный класс имеет четыре свойства.

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

Читайте также:  Функция определяющая является ли число простым питон

Итак, если мы создадим только объект производного класса, у нас все равно будет доступ к свойству базового класса благодаря функции super().

Пример функции super() в Python

Пример 2

Когда вы определяете метод родительского класса в дочернем классе, этот процесс называется переопределением.

Другими словами, дочерний класс может переопределить методы своего родителя или суперкласса, определив функцию с тем же именем.

Тем не менее, есть некоторые правила переопределения:

  1. Имя метода должно совпадать с его параметрами.
  2. Если метод суперкласса является закрытым(с префиксом с двойным подчеркиванием), вы не можете его переопределить.

В Python вы можете использовать метод super() для переопределения. Он имеет следующий синтаксис.

Источник

Python super() — Python 3 super()

Python super() - Python 3 super()

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Python super() function allows us to refer to the parent class explicitly. It’s useful in case of inheritance where we want to call super class functions.

Python super

To understand about python super function, you have to know about Python Inheritance. In Python Inheritance, the subclasses inherit from the superclass. Python super() function allows us to refer the superclass implicitly. So, Python super makes our task easier and comfortable. While referring the superclass from the subclass, we don’t need to write the name of superclass explicitly. In the following sections, we will discuss python super function.

Python super function example

At first, just look at the following code we used in our Python Inheritance tutorial. In that example code, the superclass was Person and the subclass was Student . So the code is shown below.

class Person: # initializing the variables name = "" age = 0 # defining constructor def __init__(self, person_name, person_age): self.name = person_name self.age = person_age # defining class methods def show_name(self): print(self.name) def show_age(self): print(self.age) # definition of subclass starts here class Student(Person): studentId = "" def __init__(self, student_name, student_age, student_id): Person.__init__(self, student_name, student_age) self.studentId = student_id def get_id(self): return self.studentId # returns the value of student id # end of subclass definition # Create an object of the superclass person1 = Person("Richard", 23) # call member methods of the objects person1.show_age() # Create an object of the subclass student1 = Student("Max", 22, "102") print(student1.get_id()) student1.show_name() 
Person.__init__(self, student_name, student_age) 
super().__init__(student_name, student_age) 

python super, python 3 super

The output will remain the same in both the cases, as shown in the below image.

Python 3 super

Note that the above syntax is for python 3 super function. If you are on python 2.x versions, then it’s slightly different and you will have to do the following changes:

class Person(object): . super(Student, self).__init__(student_name, student_age) 

The first change is to have object as the base class for Person. It’s required to use the super function in Python 2.x versions. Otherwise, you will get the following error.

Traceback (most recent call last): File "super_example.py", line 40, in student1 = Student("Max", 22, "102") File "super_example.py", line 25, in __init__ super(Student, self).__init__(student_name, student_age) TypeError: must be type, not classobj 

The second change in the syntax of the super function itself. As you can see that python 3 super function is a lot easier to use and the syntax is also clean looking.

Python super function with multilevel inheritance

As we have stated previously that Python super() function allows us to refer the superclass implicitly. But in the case of multi-level inheritances which class will it refer? Well, Python super() will always refer the immediate superclass. Also Python super() function not only can refer the __init__() function but also can call all other function of the superclass. So, in the following example, we will see that.

class A: def __init__(self): print('Initializing: class A') def sub_method(self, b): print('Printing from class A:', b) class B(A): def __init__(self): print('Initializing: class B') super().__init__() def sub_method(self, b): print('Printing from class B:', b) super().sub_method(b + 1) class C(B): def __init__(self): print('Initializing: class C') super().__init__() def sub_method(self, b): print('Printing from class C:', b) super().sub_method(b + 1) if __name__ == '__main__': c = C() c.sub_method(1) 
Initializing: class C Initializing: class B Initializing: class A Printing from class C: 1 Printing from class B: 2 Printing from class A: 3 

So, from the output we can clearly see that the __init__() function of class C had been called at first, then class B and after that class A. Similar thing happened by calling sub_method() function.

Why do we need Python super function

If you have previous experience in Java language, then you should know that the base class is also called by a super object there. So, this concept is actually useful for the coders. However, Python also keeps the facility for the programmer to use superclass name to refer them. And, if your program contains multi-level inheritance, then this super() function is helpful for you. So, that’s all about python super function. Hopefully, you understood this topic. Please use the comment box for any query. You can checkout complete python script and more Python examples from our GitHub Repository. Reference: Official Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Python super() — Python 3 super()

Python super() - Python 3 super()

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Python super() function allows us to refer to the parent class explicitly. It’s useful in case of inheritance where we want to call super class functions.

Python super

To understand about python super function, you have to know about Python Inheritance. In Python Inheritance, the subclasses inherit from the superclass. Python super() function allows us to refer the superclass implicitly. So, Python super makes our task easier and comfortable. While referring the superclass from the subclass, we don’t need to write the name of superclass explicitly. In the following sections, we will discuss python super function.

Python super function example

At first, just look at the following code we used in our Python Inheritance tutorial. In that example code, the superclass was Person and the subclass was Student . So the code is shown below.

class Person: # initializing the variables name = "" age = 0 # defining constructor def __init__(self, person_name, person_age): self.name = person_name self.age = person_age # defining class methods def show_name(self): print(self.name) def show_age(self): print(self.age) # definition of subclass starts here class Student(Person): studentId = "" def __init__(self, student_name, student_age, student_id): Person.__init__(self, student_name, student_age) self.studentId = student_id def get_id(self): return self.studentId # returns the value of student id # end of subclass definition # Create an object of the superclass person1 = Person("Richard", 23) # call member methods of the objects person1.show_age() # Create an object of the subclass student1 = Student("Max", 22, "102") print(student1.get_id()) student1.show_name() 
Person.__init__(self, student_name, student_age) 
super().__init__(student_name, student_age) 

python super, python 3 super

The output will remain the same in both the cases, as shown in the below image.

Python 3 super

Note that the above syntax is for python 3 super function. If you are on python 2.x versions, then it’s slightly different and you will have to do the following changes:

class Person(object): . super(Student, self).__init__(student_name, student_age) 

The first change is to have object as the base class for Person. It’s required to use the super function in Python 2.x versions. Otherwise, you will get the following error.

Traceback (most recent call last): File "super_example.py", line 40, in student1 = Student("Max", 22, "102") File "super_example.py", line 25, in __init__ super(Student, self).__init__(student_name, student_age) TypeError: must be type, not classobj 

The second change in the syntax of the super function itself. As you can see that python 3 super function is a lot easier to use and the syntax is also clean looking.

Python super function with multilevel inheritance

As we have stated previously that Python super() function allows us to refer the superclass implicitly. But in the case of multi-level inheritances which class will it refer? Well, Python super() will always refer the immediate superclass. Also Python super() function not only can refer the __init__() function but also can call all other function of the superclass. So, in the following example, we will see that.

class A: def __init__(self): print('Initializing: class A') def sub_method(self, b): print('Printing from class A:', b) class B(A): def __init__(self): print('Initializing: class B') super().__init__() def sub_method(self, b): print('Printing from class B:', b) super().sub_method(b + 1) class C(B): def __init__(self): print('Initializing: class C') super().__init__() def sub_method(self, b): print('Printing from class C:', b) super().sub_method(b + 1) if __name__ == '__main__': c = C() c.sub_method(1) 
Initializing: class C Initializing: class B Initializing: class A Printing from class C: 1 Printing from class B: 2 Printing from class A: 3 

So, from the output we can clearly see that the __init__() function of class C had been called at first, then class B and after that class A. Similar thing happened by calling sub_method() function.

Why do we need Python super function

If you have previous experience in Java language, then you should know that the base class is also called by a super object there. So, this concept is actually useful for the coders. However, Python also keeps the facility for the programmer to use superclass name to refer them. And, if your program contains multi-level inheritance, then this super() function is helpful for you. So, that’s all about python super function. Hopefully, you understood this topic. Please use the comment box for any query. You can checkout complete python script and more Python examples from our GitHub Repository. Reference: Official Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

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