继承:通过子类继承父类信息而达到子类可以扩展功能的目的
多重继承:通过子类继承多个类
一、多重继承一类
套用廖雪峰的例子:
https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0013868200511568dd94e77b21d4b8597ede8bf65c36bcd000
- Dog - 狗狗;
- Bat - 蝙蝠;
- Parrot - 鹦鹉;
- Ostrich - 鸵鸟。
按哺乳和鸟类分:
按跑和飞分:
总的:
程序:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Animal(object):
pass
# 大类:
class Mammal(Animal):
pass
class Bird(Animal):
pass
#功能
class Runnable(object):
def run(self):
print('Running...')
class Flyable(object):
def fly(self):
print('Flying...')
# 各种动物:
class Dog(Mammal, Runnable):
pass
class Bat(Mammal, Flyable):
pass
class Parrot(Bird, Flyable):
pass
class Ostrich(Bird, Runnable):
pass
dog = Dog()
dog.run()
运行结果:Running...
二、多重继承二类:Mixin
除了大类,其他继承的类,只要在类名后面+Mixin就可以了。
程序:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Animal(object):
pass
# 大类:
class Mammal(Animal):
pass
class Bird(Animal):
pass
#功能
class RunnableMixin(object):
def run(self):
print('Running...')
class FlyableMixin(object):
def fly(self):
print('Flying...')
# 各种动物:
class Dog(Mammal, RunnableMixin):
pass
class Bat(Mammal, FlyableMixin):
pass
class Parrot(Bird, FlyableMixin):
pass
class Ostrich(Bird, RunnableMixin):
dog = Dog()
dog.run()
运行结果:Running...
最后发现,一类和二类没啥区别。。。。。。逗我呢。。。。。。。Mask一下,日后再回头看。
原文地址:http://blog.51cto.com/13502993/2147344