首頁 >後端開發 >Python教學 >詳解python中的TypeError錯誤解決方法

詳解python中的TypeError錯誤解決方法

高洛峰
高洛峰原創
2017-03-27 16:52:1614405瀏覽

新手在學習python時候,會遇到很多的坑,下面來具體說說其中一個。

在使用python編寫物件導向的程式時,新手可能會遇到TypeError: this constructor takes no arguments這個錯誤。

例如下面的程序:

class Ball:
     def _init_(self,color,size,direction):
           self.color=color##  size
           self.direction=direction

     def bounce(self):
        . f.direction="up"

myBall=Ball("red","small","down")
print "I just created a ball."
print "My ball is",myBall.size
#print "My ball is" ,myBall.color
print "My ball's direction is",myBall.direction
print "Now I'm going to bounce the ball"
print
myBall.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.direction=direction

     def bounce(self):
          irection="up"

myBall =Ball("red","small","down")
print "I just created a ball."
print "My ball is",myBall.size
print "My ball is", myBall.color
print "My ball's direction is",myBall.direction
print "Now I'm going to bounce the ball"
print
myBall.bounce()
print "Now the ball's direction is",myBall.direction


這是正確的運行結果:

#=================== ==== RESTART: H:\python\bounce1.py =======================

I just created a ball.

My ball is small

My ball is red

My ball's direction is down
Now I'm going to bounce the ball

Now the ball's direction is up

#

以上是詳解python中的TypeError錯誤解決方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn