1、Super使用方法
super()函数在Python中用于调用父类的方法。它返回一个代理对象,可以通过该对象调用父类的方法。
要使用super()方法,需要在子类的方法中调用super(),并指定子类本身以及方法的名称。这样就可以在子类中调用父类的方法。
以下是使用super()方法的示例:
class Parent:def __init__(self):self.name = "Parent"def greet(self):print("Hello, I am", self.name)class Child(Parent):def __init__(self):super().__init__()self.name = "Child"def greet(self):super().greet()print("Nice to meet you!")child = Child()
child.greet()
输出结果为:
Hello, I am Child
Nice to meet you!
在上面的例子中,Child类继承自Parent类。在Child类的__init__方法中,我们通过super().__init__()调用了父类的__init__方法。这样就可以在子类的__init__方法中执行父类的初始化逻辑。
在Child类的greet方法中,我们首先通过super().greet()调用了父类的greet方法,然后打印出一条额外的信息。这样就可以在子类的方法中扩展父类的功能。
注意,在Python 2.x版本中,我们需要使用super(Child, self)来调用父类的方法,而不是super()。
2、不支持示例
class ParentA:def greet(self):print("Hello from Parent A")class ParentB:def greet(self):print("Hello from Parent B")class Child(ParentA, ParentB):def greet(self):super(Child, self).greet()  # 默认调用第一个父类的方法super(ParentB,self).gret()  # 显式调用第一个父类的方法child = Child()
child.greet()

3、正确示例
class ParentA:def greet(self):print("Hello from Parent A")class ParentB:def greet(self):print("Hello from Parent B")class Child(ParentA, ParentB):def greet(self):super(Child, self).greet()  # 默认调用第一个父类的方法ParentB.greet(self)  # 显式调用第二个父类的方法child = Child()
child.greet()