继承
继承
继承就是派生类(子类)继承超类(父类)的特征和行为,使得派生类对象具有超类的属性和方法,或派生类从超类继承方法,使得派生类具有超类相同的行为。
之前案例中的狗和猫,我们可以进一步抽象:
狗子抽象为狗类。
猫子抽象为猫类。
都有名字,都会叫(只是叫声不同)。
狗猫都是动物。
单继承
单继承就是继承一个类
单继承代码
#!/usr/bin/env python
class Animal(object):
def __init__(self,name):
self.name = name
def get_name(self):
return self.name
def set_name(self,value):
self.name = value
def make_sound(self):
pass
class Dog(Animal):
def make_sound(self):
print(self.get_name() + " is making sound wangwangwang")
class Cat(Animal):
def make_sound(self):
print(self.get_name() + " is making sound miaomiaomiao")
dog = Dog("史派克")
dog.make_sound()
cat = Cat("Tom")
cat.make_sound()
运行结果
┌──(root㉿kali)-[~/python_code/python_3]
└─# python animal.py
史派克 is making sound wangwangwang
Tom is making sound miaomiaomiao
注意:make_sound()方法需要在派生类中重写,因为叫声不一样。
多继承
多继承就是继承多个类
多继承代码
#!/usr/bin/env python
class A:
def __init__(self):
self.name = "burgess"
def course_A(self):
print("---------Python----------")
class B:
def __init__(self):
self.name = "burgess0x"
def course_B(self):
print("----------C++------------")
class C(A,B):
def __init__(self):
A.__init__(self)
B.__init__(self)
def study(self):
print("------Python---C++----------")
person = C()
person.course_A()
person.course_B()
person.study()
运行结果
┌──(root㉿kali)-[~/python_code/python_3]
└─# python duo.py
---------Python----------
----------C++------------
------Python---C++----------
如果A类和B类有相同的方法,那调用谁的呢?
改一下上面的代码
#!/usr/bin/env python
class A:
def __init__(self):
self.name = "burgess"
def course_A(self):
print("---------Python----------")
class B:
def __init__(self):
self.name = "burgess0x"
#改成course_A()
def course_A(self):
print("----------C++------------")
class C(A,B):
def __init__(self):
A.__init__(self)
B.__init__(self)
def study(self):
print("------Python---C++----------")
person = C()
person.course_A()
运行结果
┌──(root㉿kali)-[~/python_code/python_3]
└─# python duo.py
---------Python----------
我们可以使用mro()来查看继承调用解析方法的顺序
#!/usr/bin/env python
class A:
def __init__(self):
self.name = "burgess"
def course_A(self):
print("---------Python----------")
class B:
def __init__(self):
self.name = "burgess0x"
#改成course_A()
def course_A(self):
print("----------C++------------")
class C(A,B):
def __init__(self):
A.__init__(self)
B.__init__(self)
def study(self):
print("------Python---C++----------")
person = C()
print(C.mro())
运行结果
┌──(root㉿kali)-[~/python_code/python_3]
└─# python duo.py
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]
可以看到是C->A->B->object
浙公网安备 33010602011771号