【Python学习日记】B站小甲鱼:继承,super和多重继承

  被继承的类被称作父类,基类或超类。

  定义子类只需要在子类的类名后的括号里添加父类的类名就可以了。

class Parent():
    def hello(self):
        print('正在调用父类...')
class Child(Parent):
    pass
p = Parent()
c = Child()
p.hello()
print('*')
c.hello()

  上述程序的输出是

正在调用父类...
*
正在调用父类...

  继承的写法非常简单。需要注意的是,如果子类的类名或方法名与父类相同,则会覆盖掉父类或父类的方法。

class Parent():
    def hello(self):
        print('正在调用父类...')
class Child(Parent):
    def hello(self):
        print('正在调用子类...')
p = Parent()
c = Child()
p.hello()
print('*')
c.hello()
print('*')
p.hello()

  例如上述程序的输出是

正在调用父类...
*
正在调用子类...
*
正在调用父类...

  虽然子类覆盖了父类的hello方法但是并不影响父类方法的内容,只是说子类在调用hello方法的时候不再引用父类的方法嘞。

下面这个例子来说明继承关系

import random as r

class Fish():
    def __init__(self):
        self.x = r.randint(0,10)
        self.y = r.randint(0,10)
    def move(self):
        self.x -=r.randint(0,3)
        self.y +=r.randint(0,3)
        print("当前所在的位置是:",self.x,self.y)

class Goldfish(Fish):
    pass
class Carp(Fish):
    pass
class Salmon(Fish):
    pass

class Shark(Fish):
    def __init__(self):
        self.hungry = True
    def eat(self):
        if self.hungry == True:
            print('我要开始吃啦')
            self.hungry = False
        else:
            print('我吃饱了')

fish = Fish()
goldfish =Goldfish()
carp = Carp()
shark = Shark()

goldfish.move()
goldfish.move()
goldfish.move()
shark.eat()
shark.eat()

上面程序的输出是

当前所在的位置是: 6 1
当前所在的位置是: 4 4
当前所在的位置是: 1 6
我要开始吃啦
我吃饱了

但是如果要调用shark.move()的时候程序就会报错,因为找不到x这个变量,原因就是在shark这个子类中方法__init__()覆盖了父类中的方法,因此在子类中如果还要应用父类的方法的时候,子类的方法中应该包含父类的名字,比如这样就搞定了。

class Shark(Fish):
    def __init__(self):
        Fish.__init__(self)
        self.hungry = True

在Python中可以是用super函数可以自动找到子类的方法并自动传入参数

class Shark(Fish):
    def __init__(self):
        super().__init__()
        self.hungry = True

同样也就可以调用move的方法嘞。super就是可以直接调用父类的方法。

Python也支持多重继承。

只要在子类的定义里把多个父类的名字写在()里就可以了。

class Base1:
    def foo1(self):
        print("我是土豆")

class Base2:
    def foo2(self):
        print("我是西瓜")

class C(Base1,Base2):
    pass

c =C()
c.foo1()
c.foo2()

上面程序的输出是

我是土豆
我是西瓜

多重继承虽然看起来很牛逼,但可能会导致代码混乱。因此尽量少用。

原文地址:https://www.cnblogs.com/JodyJoy1201/p/13653946.html