neolee / wop

零基础编程思维与实践课程《欢迎进入编程世界》主站
94 stars 79 forks source link

继承自两个父类时出现的问题 #87

Closed dishangti closed 3 years ago

dishangti commented 3 years ago

I tried to create a new class extended from oth 2 classes.

class Animal:
    live = ""

    def __init__(self, name):
        self.name = name

    def voice(self):
        pass

    def eat(self):
        print("Eat some food!")

class Pet:
    def play_with(self):
        print("Have a nice time!")

class Cat(Animal, Pet):
    live = "land"

    def voice(self):
        print("Meow!")

    def play_with(self):
        print("Meow Meow!")

class Dog(Animal, Pet):
    live = "land"

    def eat():
        print("Eat some meat!")

a = Cat("mikey")
b = Dog("pupy")
for animal in [a, b]:
    print(animal.play_with())

Expected Output: Meow Meow! Have a nice time!

Output in reality: Meow Meow! None Have a nice time! None

I wonder what "None" is.

neolee commented 3 years ago

Python 是支持多重继承的,也就是一个类可以继承多个基类,得到所有基类的所有 features。

所以你遇到的问题和继承机制没啥关系,是别的问题。仔细思考一下下面这句代码做了哪些事情:

print(animal.play_with())

这句其实做了两件事:

  1. 调用函数 animal.play_with(),即执行了这个函数内容——想一想这个函数的定义中做了什么;
  2. 打印函数 animal.play_with() 的返回值——想一想这个函数的返回值是什么。
dishangti commented 3 years ago

@neolee 哦哦知道了它隐式地返回了一个None,谢谢老师