【问题标题】:Python class Inheritance queryPython类继承查询
【发布时间】:2018-12-01 15:02:30
【问题描述】:

我在 python 多级类继承中遇到错误。
这是我的代码:

class Animal():
    def __init__(self):
        print("Animal created")
    def whoAmI(self):
        print("Animal")
    def eat(self):
        print('eating')

class Dog(Animal):
    print("dog created")

class Cat(Dog):
    print("car created")

m = Cat()
Cat.eat()

这是我得到的错误:

【问题讨论】:

  • 我认为你的意思是让你的 Cat 类继承自 Animal,而不是 Dog
  • @Planet 我的回答对你有帮助吗?
  • @TobiasWilfert thnks 它帮助了我!
  • 接受@TobiasWilfert

标签: python class inheritance compiler-errors multi-level


【解决方案1】:

你的代码应该是这样的:

m = Cat()
m.eat()

m 是类Cat 的一个实例,因此,您可以在其上调用eat()。除非你说Cat().eat(),否则你不能在Cat 上调用eat。
这与继承关系不大,因为这段代码也会给你一个错误:

Animal.eat()

另外,cat 应该直接继承自 Animal 而不是 dog。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多