1. 继承
继承具有传递性
当父类方法的实现不能满足子类的需求的时候
可以对父类方法进行重写
1.覆盖父类方法
2.对父类的方法进行扩展
2. 继承示例
class Animal:
def eat(self):
print('吃!!!')
def drink(self):
print('喝!!!')
def run(self):
print('跑!!!')
def sleep(self):
print('睡!!!')
class Cat(Animal):
# def eat(self):
# print('吃!!!')
# def drink(self):
# print('喝!!!')
# def run(self):
# print('跑!!!')
# def sleep(self):
# print('睡!!!')
def call(self):
print('喵喵!!')
class Hellokitty(Cat):
def speak(self):
print('我可以说话')
def call(self):
# 调用原本在父类中封装的方法
super().call()
# Cat.call(self) python2.x
# 针对子类特有的需求 编写代码
print('#%@@#$#@%')
class Dog(Animal):
pass
cat = Hellokitty()
cat.eat()
cat.drink()
cat.run()
cat.call()
dog = Dog()
dog.run()
dog.eat()
3. 继承的顺序
class A:
def test(self):
print('A----test方法')
def demo(self):
print('A----demo方法')
class B:
def test(self):
print('B----test方法')
def demo(self):
print('B----demo方法')
class C(A,B):
pass
c = C()
c.test()
c.demo()
4. 新式类和旧式(经典)类
object是Python为所有对象提供的基类,提供有一些内置的属性和方法,可以使用dir函数查看
新式类:以object为基类的类
经典类 不以object为基类的类
在python3.X中定义的类时,如果没有指定父类,会默认使用object作为基类–python3.x中定义的类都是新式类
在python2.x中定义类时,如果没有指定父类,则不会以object作为基类
为保证编写的代码能够同时在python2.x和python3.x运行
今后在定义类时,如果没有父类,建议统一继承自object
5. 初始化方法的继承(扩展)
class Bird(object):
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print('$$@#%@%')
self.hungry = False
else:
print('No thanks')
class SongBird(Bird):
def __init__(self):
super().__init__()
self.sound = 'aaaaaa'
def sing(self):
print(self.sound)
bird = SongBird()
bird.eat()
bird.sing()
print(bird.hungry)