Python super()– Python 3 super()
Python super()函数允许我们显式引用父类。
在继承的情况下,我们要调用超类函数很有用。
Python super
要了解python超级功能,您必须了解Python继承。
在Python继承中,子类从超类继承。
Python super()函数允许我们隐式引用超类。
因此,Python super使我们的任务更加轻松和舒适。
从子类中引用超类时,我们不需要显式地编写超类的名称。
在以下各节中,我们将讨论python超级功能。
Python super函数示例
首先,请看一下我们在Python继承教程中使用的以下代码。
在该示例代码中,超类是" 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)
我们可以将其替换为python超级函数调用,如下所示。
super().__init__(student_name, student_age)
两种情况下的输出将保持不变.
Python 3 super
请注意,以上语法适用于python 3超级功能。
如果您使用的是python 2.x版本,则略有不同,您将需要进行以下更改:
class Person(object): ... super(Student, self).__init__(student_name, student_age)
第一个更改是将"对象"作为Person的基类。
必须在Python 2.x版本中使用超级功能。
否则,您将得到以下错误。
Traceback (most recent call last): File "super_example.py", line 40, in <module> 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超级函数易于使用,语法也很简洁。
具有多级继承的Python super函数
如前所述,Python super()函数允许我们隐式引用超类。
但是在多级继承的情况下,它将引用哪个类?好吧,Python super()将始终引用直接超类。
Python 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 super示例的输出。
Initializing: class C Initializing: class B Initializing: class A Printing from class C: 1 Printing from class B: 2 Printing from class A: 3
因此,从输出中我们可以清楚地看到,首先调用了C类的__init __()函数,然后调用了B类,再调用了A类。
通过调用sub_method()函数发生了类似的情况。
为什么我们需要Python super函数
如果您以前有Java语言的经验,那么您应该知道那里的超级对象也调用了基类。
因此,这个概念实际上对编码人员很有用。
但是,Python还为程序员保留了使用超类名称来引用它们的便利。
而且,如果您的程序包含多级继承,那么此super()函数将对您有所帮助。