Python super() 函数是一个内置函数,它允许我们在子类中调用超类的方法或属性。无需提及父类的名称即可访问其中存在的方法。
使用此函数的一个好处是,即使继承层次结构发生变化, super() 也将始终引用正确的超类,而无需在子类中进行任何修改。
语法
以下是 Python super() 函数的语法 -
super()
参数
Python super() 函数不接受任何参数。
返回值
此函数返回返回表示父类的对象。
super() 函数示例
练习以下示例来理解 Python 中 super() 函数的用法:
示例:使用 super() 函数
以下示例实际演示了 Python super() 函数的用法。在这里,我们定义了单级继承,并尝试调用 Parent 类的 __init__ 方法。
class Company:
def __init__(self, orgName):
self.orgName = orgName
class Employee(Company):
def __init__(self, orgName, empName):
super().__init__(orgName)
self.empName = empName
employee = Employee("qikepu", "Shrey")
print("Accessing parent class properties:")
print(employee.orgName)
当我们运行上述程序时,它会产生以下结果——
Accessing parent class properties:
qikepu
qikepu
示例:使用 super() 函数覆盖父类方法
super() 函数可用于覆盖父类的任何方法,如下面的代码所示。在这里,我们覆盖了名为 “newMsg” 的方法。
class Message:
def newMsg(self):
print("Welcome to qikepu!!")
class SendMsg(Message):
def newMsg(self):
print("You are on qikepu!!")
super().newMsg()
sendMsg = SendMsg()
print("Overriding parent class method:")
sendMsg.newMsg()
以下是上述代码的输出 -
Overriding parent class method:
You are on qikepu!!
Welcome to qikepu!!
You are on qikepu!!
Welcome to qikepu!!
示例:在多重继承中使用 super() 函数
下面的代码演示了如何在多重继承中使用 super() 访问父类。
class Organisation:
def __init__(self, orgName):
self.orgName = orgName
class Hr(Organisation):
def __init__(self, orgName, hrName):
super().__init__(orgName)
self.hrName = hrName
class Employee(Hr):
def __init__(self, orgName, hrName, empName):
super().__init__(orgName, hrName)
self.empName = empName
emp = Employee("qikepu", "K. Raja", "Shrey")
print(f"Organisation Name: {emp.orgName}")
print(f"HR Name: {emp.hrName}")
print(f"Employee Name: {emp.empName}")
上述代码的输出如下 -
Organisation Name: qikepu
HR Name: K. Raja
Employee Name: Shrey
HR Name: K. Raja
Employee Name: Shrey