- 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 -=1 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: print('吃货的梦想就是天天吃肉!') self.hungry = False else: print('吃撑了!')
>>> fish = Fish()>>> fish.move() 我的位置 4 7>>> goldfish = Goldfish()>>> goldfish.move() 我的位置 6 5>>> carp = Carp()>>> carp.move() 我的位置 7 6>>> salmon = Salmon()>>> salmon.move() 我的位置 -1 10>>> shark = Shark()>>> shark.move()Traceback (most recent call last):File "<pyshell#9>", line 1, in <module>shark.move()File "/Users/yixia/Desktop/fish.py", line 9, in moveself.x -=1AttributeError: 'Shark' object has no attribute 'x'
--- 报错的原因: AttributeError: 'Shark' object has no attribute 'x' :Shark 没有 x 的属性, shark 继承了 Fish, 为什么会没有 x 的属性呢
原因: Shark 重写了__init__的方法, 就会覆盖父类 Fish 的__init__() 方法中的 x 属性, 即: 子类定义类一个和父类相同名称的方法, 则会覆盖父类的方法和属性
改正的代码:
两种方法: 1, 调用未绑定的父类方法 2, 使用 super() 函数
实现的代码如下:
第一种:
- 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 -=1 print('我的位置',self.x,self.y)
- class Goldfish(Fish): pass
- class Carp(Fish): pass
- class Salmon(Fish): pass
- class Shark(Fish): def __init__(self): Fish.__init__(self) #父类名称调用__init__() 函数 self.hungry = True
- def eat(self): if self.hungry: print('吃货的梦想就是天天吃肉!') self.hungry = False else: print('吃撑了!')
>>> shark = Shark()>>> shark.move() 我的位置 1 8>>>
第二种:
- 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 -=1 print('我的位置',self.x,self.y)
- class Goldfish(Fish): pass
- class Carp(Fish): pass
- class Salmon(Fish): pass
- class Shark(Fish): def __init__(self): super().__init__() #采用 super() 函数 self.hungry = True
- def eat(self): if self.hungry: print('吃货的梦想就是天天吃肉!') self.hungry = False else: print('吃撑了!')
>>> shark = Shark()>>> shark.move() 我的位置 -1 6
来源: http://www.bubuko.com/infodetail-2746495.html