Calling super method python

Функция super() в Python

Функция super() в Python позволяет нам явно ссылаться на родительский класс. Это полезно в случае наследования, когда мы хотим вызывать функции суперкласса. В Python Inheritance подклассы наследуются от суперкласса.

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

Пример функции

Сначала просто посмотрите на следующий код, который мы использовали в нашем руководстве по наследованию. В этом примере кода суперклассом был Person, а подклассом – Student. Итак, код показан ниже.

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 tuple contains tuple

Функция super() в python

Функция для Python 3

Обратите внимание, что приведенный выше синтаксис предназначен для функции super() в python 3. Если вы используете версию Python 2.x, она немного отличается, и вам придется внести следующие изменения:

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

Первое изменение – сделать объект базовым классом для Person. В версиях Python 2.x необходимо использовать функцию super. В противном случае вы получите следующую ошибку:

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

Второе изменение синтаксиса самой функции. Как видите, функция в python 3 намного проще в использовании, и синтаксис также выглядит чистым.

Функция super() с многоуровневым наследованием

Как мы уже заявляли ранее, super() позволяет нам неявно ссылаться на суперкласс.

Но в случае многоуровневого наследования, к какому классу оно будет относиться? super() всегда будет ссылаться на непосредственный суперкласс.

Также функция может не только ссылаться на функцию __init __(), но также может вызывать все другие функции суперкласса. Итак, в следующем примере мы увидим это:

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)

Давайте посмотрим на результат вышеприведенного примера в python 3 с многоуровневым наследованием.

Initializing: class C Initializing: class B Initializing: class A Printing from class C: 1 Printing from class B: 2 Printing from class A: 3

Итак, из выходных данных мы ясно видим, что сначала была вызвана функция __init __() класса C, затем класса B, а затем класса A. Аналогичная вещь произошла при вызове функции sub_method().

Зачем нужна функция super()?

Если у вас есть предыдущий опыт работы с языком Java, вы должны знать, что базовый класс также вызывается там супер объектом. Итак, эта концепция действительно полезна для кодеров. Однако Python также позволяет программисту использовать имя суперкласса для ссылки на него. И, если ваша программа содержит многоуровневое наследование, эта функция будет вам полезна.

Источник

Understanding the super() Method in Python

The Super() Method In Python

Today in this tutorial, we are going to discuss the super() method in Python.

Before diving right into the topic, we highly recommend going through the tutorial on Python Inheritance.

Once you know about inheritance in Python, we can get started.

The super() Method in Python

The super method returns a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.

Or simply, it is used to call the constructor, i.e. the __init__() method of the superclass.

Syntax for using super in Python is given below.

In Python 3.x versions, we can use super without passing the above two parameters. Look at the code snippet below.

class C(B): def method(self, arg): super().method(arg)

Here, C is the derived class, B is the base class, method is a user defined function with argument arg .

As you can see, the line super().method(arg) is actually equivalent to super( C, self).method(arg) in Python 3.x. This is not allowed in Python 2.x. Hence, using super there is a bit tricky.

Using super()

Consider the below given example.

class Demo: a = 0 b = 0 c = 0 def __init__(self,A,B,C): self.a = A self.b = B self.c = C def display(self): print(self.a, self.b, self.c) class Newdemo(Demo): d = 0 def __init__(self,A,B,C,D): self.a = A self.b = B self.c = C self.d = D def display(self): print(self.a, self.b, self.c,self.d) B1 = Demo(100,200,300) print("Contents of Base Class:") B1.display() D1 = Newdemo(10,20,30,40) print("Contents of Derived Class:") D1.display()

Output1

In the above example, the classes derived from the base class Demo were not implemented efficiently or robustly.

The derived class Newdemo explicitly initializes the value of A, B, and C fields of the base class. The same duplication of code is found while initialization of the same fields in the base class, Demo too.

This process is inefficient. This implies that a subclass must be granted access to the members of a superclass.

Therefore, whenever a subclass needs to refer to its immediate super class, super comes into the picture.

Super() to Call Super Class Constructor

Now let us apply the super() method for the above example.

class Demo: a = 0 b = 0 c = 0 def __init__(self,A,B,C): self.a = A self.b = B self.c = C def display(self): print(self.a, self.b, self.c) class Newdemo(Demo): d = 0 def __init__(self,A,B,C,D): self.d = D super().__init__(A,B,C) #super to call super Class #The __init__() Method def display(self): print(self.a, self.b, self.c,self.d) B1 = Demo(12,34,56) print("Contents of Base Class:") B1.display() D1 = Newdemo(11,22,33,44) print("Contents of Derived Class:") D1.display()

Output

Here, the derived class Newdemo calls the super() with arguments a, b, and c. This causes the constructor __init__ of the base class, i.e. Demo to be called. This initialises the values of a, b, and c. Hence, the Newdemo class no longer initialises the values itself.

Using super in Python 2.x

The syntax to call a super class constructor in Python 2.x is given below,

super(Derived_Class_Name, self).__init__(Parameters_of_Super_Class_Constructor)

Hence we need to make some minor changes to the above example if we want to use it in Python 2.

Firstly, we need to put object in the base class as shown below.

class Demo(object): . #other statements

And secondly, pass Newdemo and self at the site of super class call. Like this.

super(Newdemo,self).__init__(A,B,C) #super to call super Class . #The __init__() Method

Why we need super()

In the case of single inheritance with a parent and offspring class, the super function is used to implicitly refer to the parent class without naming it explicitly. This makes the code more efficient, maintainable and robust in nature.

Nextly, for a multi-level inheritance, the super method can be used to refer to the immediate superclass implicitly. This again makes the code easier to understand and highly maintainable.

Conclusion

So in this tutorial we understood the concept of super() method in Python, its use and need.

For any further questions, feel free to comment below.

References

  • Python Super – Journal Dev Post,
  • What does ‘super’ do in Python? – StackOverflow Question,
  • Python super – Official Documentation.

Источник

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