Python怎么调用子类里面的函数
在Python中,子类继承了父类的所有属性和方法。当我们创建一个子类的实例时,可以直接调用子类的方法。但是,如果子类中定义了与父类同名的方法,那么如何调用子类中的方法呢?本文将介绍Python中调用子类方法的几种方式,并通过一个实际问题来解释。
问题描述
假设我们有一个电商平台的应用程序,需要实现一个商品类(Product)和一个电子书类(Ebook)。商品类有一个display_info
方法用于显示商品的名称和价格,电子书类继承了商品类,并扩展了一个display_info
方法,用于显示电子书的名称、价格和作者。我们需要根据具体情况来调用商品类或电子书类的display_info
方法。
解决方法
方法一:使用父类名称调用子类方法
在Python中,可以使用父类名称来调用子类方法。以下是示例代码:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def display_info(self):
print(f"商品名称:{self.name}")
print(f"商品价格:{self.price}")
class Ebook(Product):
def __init__(self, name, price, author):
super().__init__(name, price)
self.author = author
def display_info(self):
super().display_info()
print(f"电子书作者:{self.author}")
product = Product("商品A", 100)
product.display_info()
ebook = Ebook("电子书B", 50, "作者C")
ebook.display_info()
运行以上代码,输出结果为:
商品名称:商品A
商品价格:100
商品名称:电子书B
商品价格:50
电子书作者:作者C
在示例代码中,我们定义了一个商品类(Product)和一个电子书类(Ebook)。商品类有一个display_info
方法用于显示商品的名称和价格,电子书类继承了商品类,并扩展了一个display_info
方法,用于显示电子书的名称、价格和作者。
在子类Ebook
的display_info
方法中,我们首先调用super().display_info()
来调用父类Product
的display_info
方法,然后再输出电子书的作者信息。
方法二:使用super
函数调用父类方法
除了使用父类名称来调用子类方法外,还可以使用super
函数来调用父类方法。以下是示例代码:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def display_info(self):
print(f"商品名称:{self.name}")
print(f"商品价格:{self.price}")
class Ebook(Product):
def __init__(self, name, price, author):
super().__init__(name, price)
self.author = author
def display_info(self):
super().display_info()
print(f"电子书作者:{self.author}")
product = Product("商品A", 100)
product.display_info()
ebook = Ebook("电子书B", 50, "作者C")
ebook.display_info()
运行以上代码,输出结果与方法一相同。
在示例代码中,我们使用super().__init__(name, price)
调用父类Product
的__init__
方法来初始化商品类的属性。同样地,在子类Ebook
的display_info
方法中,我们使用super().display_info()
来调用父类Product
的display_info
方法。
方法三:通过对象调用方法
在Python中,可以通过对象调用方法,如果对象是子类的实例,则会调用子类方法。以下是示例代码:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def display_info(self):
print(f"商品名称:{self.name}")
print(f"商品价格:{self.price}")
class Ebook(Product):
def __init__(self, name, price, author):
super().__init__(name, price)
self.author = author
def display_info(self):
super().display_info()
print(f"电子书作者:{self.author}")
product = Product("商品A", 100)
product.display_info()
ebook = Ebook("电子书B", 50, "作者C")
ebook.display_info