2018-10-24
阅读量:
792
python 错误解析(二十三)
代码如下:
>>>def A():
return A()
>>>A() #无限循环,等消耗掉所有内存资源后,报最大递归深度的错误
File "<pyshell#2>", line 2, in A return A()RuntimeError: maximum recursion depth exceeded
class Bird:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print "Ahaha..."
self.hungry = False
else:
print "No, Thanks!"
该类定义鸟的基本功能吃,吃饱了就不再吃
输出结果:
代码如下:
>>> b = Bird()
>>> b.eat()
Ahaha...
>>> b.eat()
No, Thanks!
下面一个子类SingBird,
代码如下:
class SingBird(Bird):
def __init__(self):
self.sound = 'squawk'
def sing(self):
print self.sound
输出结果:
代码如下:
>>> s = SingBird()
>>> s.sing()
squawk
SingBird是Bird的子类,但如果调用Bird类的eat()方法时,
代码如下:
>>> s.eat()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
s.eat()
File "D:\Learn\Python\Person.py", line 42, in eat
if self.hungry:
AttributeError: SingBird instance has no attribute 'hungry'
【错误分析】代码错误很清晰,SingBird中初始化代码被重写,但没有任何初始化hungry的代码
代码如下:
class SingBird(Bird):
def __init__(self):
self.sound = 'squawk'
self.hungry = Ture #加这么一句
def sing(self):
print self.sound






评论(0)


暂无数据
推荐帖子
0条评论
0条评论
1条评论