live long and prosper
覆盖
在python面向对象是编程中,我们知道可以在创建父类的基础上,再创建从父类继承过来的子类,子类可以继承父类的所有方法,但是,我们创建子类的原因是需要为子类添加一些个性化元素,比如说修改父类中的方法,或者说替代父类方法,我们称这样的行为为覆盖,覆盖掉父类中的一些方法,来满足子类中的个性需求。
现在创建一个父类:
class Car:
def __init__(self, name):
self.name = name
def print_name(self):
print("I have a car")
然后创建一个子类
class MyCar(Car):
def __int__(self, name):
self.name = name
def print_name(self):
print(f"I have a beautiful car,the name is {self.name}")
在这两个类中,应该注意到print_name方法的不同,现在先调用父类的方法:
your_car = Car("吉利")
your_car.print_name()
输出内容是:
I have a car,his name is 吉利.
然后调用子类的方法:
my_car = MyCar("奇瑞")
my_car.print_name()
输出内容是:
I have a beautiful car,the name is 奇瑞.
从上面两个父类和子类的调用方法可以看出,子类继承父类的全部方法,同时子类中对方法的调用可以覆盖父类的方法。
##
子类中的可以添加父类中没有的方法,这里借用上面的例子
class MyCar(Car):
def __int__(self, name):
self.name = name
def print_name(self):
print(f"I have a beautiful car,the name is {self.name}.")
def influence(self):
print("this kind of car is saleable.")
在子类中添加了influence的方法,调用后,输出为:
this kind of car is saleable.
但是,子类中添加的方法,在父类中不可以调用,尝试下面的例子:
your_car.influence()
尝试调用后,python报出了下面的错误:
Traceback (most recent call last):
File "D:\CODE HOUSE\python_Practise\main.py", line 379, in <module>
your_car.influence()
AttributeError: 'Car' object has no attribute 'influence'
##
如何在子类中调用父类的方法呢?,我们使用super()
根据上面的例子,我们做了一些修改。
class Car:
def __init__(self, name):
self.name = name + "is a car"
def print_name(self):
print(f"{self.name}.")
class MyCar(Car):
def __int__(self, name):
self.name = name
def print_name(self):
super().print_name()
从代码中看出,父类和子类中的初始化函数有所不同,现在,在子类中调用子类初始化函数:
在my_car类中调用了父类中的print_name()函数,使用super()
super()一定程度上体现了继承的特性,从父类中继承函数。
·super()作用是获取了父类的定义
·子类中使用super()是,向子类自动传递了父类所需要的self参数,程序员只需要传递其它参数即可。
欢迎斧正