属性不是由子类从父级继承的

时间:2018-04-16 18:08:45

标签: python inheritance

我正在学习使用python进行编码。目前,我在Obstacles和Classes但是我有这个问题,属性不会从父母转移,有时奇怪的工作。什么似乎是问题?

>>> class Things:
    pass

>>> class Inanimate(Things):
    pass

>>> class Animate(Things):
    pass

>>> class Animals(Animate):
    pass

>>> class Mammals(Animals):
    pass

>>> class Giraffes(Mammals):
    pass

>>> class Animals(Animate):
    def breathe(self):
        print("breathes")


>>> class Animals(Animate):
    def move(self):
        print("moves")


>>> class Animals(Animate):
    def eat_food(self):
        print("eats food")


>>> class Animals(Animate):
    def jump(self):
        print("jumps in the air")


>>> class Mammals(Animals):
    def feeds_young_with_milk(self):
        print("feeds young with milk")


>>> class Giraffes(Mammals):
    def eat_leaves_from_trees(self):
        print("eat leaves from trees")


>>> reginald = Giraffes()
>>> reginald.move()
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    reginald.move()
AttributeError: 'Giraffes' object has no attribute 'move'
>>> reginal.breathes()
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    reginal.breathes()
NameError: name 'reginal' is not defined
>>> reginald.breathes()
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    reginald.breathes()
AttributeError: 'Giraffes' object has no attribute 'breathes'
>>> reginald.eat_food()
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    reginald.eat_food()
AttributeError: 'Giraffes' object has no attribute 'eat_food'
>>> reginald.jump()
jumps in the air
>>> 

1 个答案:

答案 0 :(得分:0)

与Ruby不同,重新定义类并不会在现有定义中添加更多内容。每次编写class Animals(Animate): ...时,您都要定义一个全新的类,该类与之前具有该名称的类没有任何关联,并替换名为{{1}的类对象用来指代。新课程没有旧方法。

停止重新定义相同的课程5次。第一次完全定义一个类。