详解python中的typeerror错误解决办法

新手在学习python时候,会遇到很多的坑,下面来具体说说其中一个。

在使用python编写面向对象的程序时,新手可能遇到typeerror: this constructor takes no arguments这个错误。

例如下面的程序:

class ball: def _init_(self,color,size,direction): self.color=color self.size=size self.direction=direction def bounce(self): if self.direction==”down”: self.direction=”up”myball=ball(“red”,”small”,”down”)print “i just created a ball.”print “my ball is”,myball.sizeprint “my ball is”,myball.colorprint “my ball’s direction is”,myball.directionprint “now i’m going to bounce the ball”printmyball.bounce()print “now the ball’s direction is”,myball.direction

运行会报错:

======================= restart: h:\python\bounce1.py =======================traceback (most recent call last): file “h:\python\bounce1.py”, line 11, in myball=ball(“red”,”small”,”down”)typeerror: this constructor takes no arguments

出错原因是,在python中构造函数书写格式是__init__,而不是_init_,即在init两侧都是双下划线,不是单下划线。

修改后如下:

class ball: def __init__(self,color,size,direction): self.color=color self.size=size self.direction=direction def bounce(self): if self.direction==”down”: self.direction=”up”myball=ball(“red”,”small”,”down”)print “i just created a ball.”print “my ball is”,myball.sizeprint “my ball is”,myball.colorprint “my ball’s direction is”,myball.directionprint “now i’m going to bounce the ball”printmyball.bounce()print “now the ball’s direction is”,myball.direction

这是正确的运行结果:

======================= restart: h:\python\bounce1.py =======================i just created a ball.my ball is smallmy ball is redmy ball’s direction is downnow i’m going to bounce the ballnow the ball’s direction is up

以上就是详解python中的typeerror错误解决办法的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类

发表评论