目录
(1)如果子类不复写__init__()方法,会自动调用父类的__init__()方法
(2)如果子类复写了__init__()方法,不会调用父类的__intit__()方法,但是这样不推荐实用
(3)如果子类继承父类的属性和方法,在子类中必须复写所有父类的属性和方法,否则会报错
第一种:from abc import ABCMeta,abstractmethod
1)..如果一个子类继承的多个父类中有相同的方法,子类该如何继承父类的方法呢?
1.封装:https://blog.csdn.net/g_optimistic/article/details/86516190
2.多态:https://blog.csdn.net/g_optimistic/article/details/86516078
1.继承的概念
让类和类之间产生父子关系,让子类可以拥有父类的属性和方法,但不能继承私有属性
继承就是可以获取另一个类中的静态属性和普通方法
2.继承的作用
提高代码的重用率
3.继承的格式
class 子类名(父类名):
....代码....
所有的类都默认继承object类
类 | 描述 | 举例 |
新式类 | 把默认继承的object类写出来 | class Animal(object): |
旧式类 | 不用把默认继承的object类写出来 | class Animal(object): |
Python提倡用新式类
4.方法的复写
(1)子类定义了和父类相同的方法
(2)复写的条件
当父类的方法不满足子类的需求的时候,就使用方法的复写
(3)调用方法的顺序
先去子类里面找,找不到再去父类,父类里面找不到就报错
class Animal(object):
type = '动物'
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print('吃...')
def sleep(self):
print('睡觉...')
class Dog(Animal):
def eat(self):
print('吃狗粮...')
def look_door(self):
print('看大门...')
class Cat(Animal):
def eat(self):
print('吃小鱼...')
def climb(self):
print('爬树...')
dog = Dog('京东狗', 8)
dog.eat() # 吃狗粮...
dog.sleep() # 睡觉...
dog.look_door() # 看大门...
cat = Cat('天猫', 10)
cat.eat() # 吃小鱼...
cat.sleep() # 睡觉...
cat.climb() # 爬树...
5.super()
当子类和父类有相同的方法的时候,子类默认调用自己的方法,不能使用父类的方法
如果想要使用父类的方法,我们就可以用super()方法来调用父类的方法
子类内部用 | 外部用 |
super().方法() | |
super(子类名,self).方法() | super(子类名.子类对象名).方法() |
父类名.方法(self) | 父类名.方法(子类对象名) |
class Animal(object):
type = '动物'
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self):
print('吃')
def sleep(self):
print('睡觉...')
class Dog(Animal):
def look_door(self):
print('看大门...')
def eat(self):
super().eat() # 调用父类的eat()方法
super(Dog, self).eat() # super(子类名,self).方法()
Animal.eat(self) # 父类名.方法(self)
print('吃狗粮...')
dog = Dog('京东狗', 8)
super(Dog, dog).eat() # super(子类名,子类对象名).方法()
Animal.eat(dog) # 父类名.方法(子类对象名)
dog.eat()
6.__init__()
(1)如果子类不复写__init__()方法,会自动调用父类的__init__()方法
(2)如果子类复写了__init__()方法,不会调用父类的__intit__()方法,但是这样不推荐实用
往后面添加super().__init__()方法就行
class Person(object):
def __in