When new users are learning python, they will encounter many pitfalls. here is a specific example. When writing object-oriented programs in python, a newbie may encounter the TypeError: thisconstructortakesnoarguments error. When new users are learning python, they will encounter many pitfalls. here is a specific example.
When writing an object-oriented program using python, a newbie may encounter the TypeError: this constructor takes no arguments error.
For example, the following program:
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. 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 ction is", myBall. direction
An error is reported during running:
===================================== 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
The error occurs because the constructor in python is written in the format of _ init __, rather than _ init _, that is, there is a double underline on both sides of init, not a single underline.
The modification is as follows:
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. 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 ction is", myBall. direction
This is the correct running result:
===================================== RESTART: H: \ python \ bounce1.py =============================
I just created a ball.
My ball is small
My ball is red
My ball's ction is down
Now I'm going to bounce the ball
Now the ball's ction is up
The above is a detailed description of the TypeError solution in python. For more information, see other related articles in the first PHP community!