Beginners in the learning of Python, will encounter a lot of pits, below to specifically say one of them.
When writing object-oriented programs using Python, newbies may encounter Typeerror:this constructor takes no arguments this 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", myball.direction
Print "Now I ' m going to bounce the ball"
Print
Myball.bounce ()
Print "Now the ball ' s direction is", myball.direction
Operation will be error:
======================= restart:h:\python\bounce1.py =======================
Traceback (most recent):
File "H:\python\bounce1.py", line one, in <module>
Myball=ball ("Red", "small", "down")
Typeerror:this constructor takes no arguments
The reason for the error is that in Python the constructor writing format is __init__, not _init_, which is double-underlined on both sides of the INIT, not single-underlined.
The following changes are followed:
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", myball.direction
Print "Now I ' m going to bounce the ball"
Print
Myball.bounce ()
Print "Now the ball ' s direction is", myball.direction
This is the correct result for the operation:
======================= restart:h:\python\bounce1.py =======================
I just created a ball.
My ball was small
my ball was red
my ball's direction is off
now I ' m going to bounce the ball
now the ball ' S direction is up