Home > Backend Development > Python Tutorial > Detailed explanation of TypeError error solutions in python

Detailed explanation of TypeError error solutions in python

高洛峰
Release: 2017-03-27 16:52:16
Original
14414 people have browsed it

Novices will encounter many pitfalls when learning python. Let’s talk about one of them in detail below.

When writing object-oriented programs in python, novices may encounter the error TypeError: this constructor takes no arguments.

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"


## This 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

will report an error when 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 reason for the error is that the writing format of the constructor in python is __init__ instead of _init_, that is, there are double underscores on both sides of init, not a single underscore.

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 direction 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 direction is down
Now I'm going to bounce the ball

Now the ball's direction is up

The above is the detailed content of Detailed explanation of TypeError error solutions in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template