Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

python - TypeError: Car() takes no arguments

I am trying to create a class. But while running the code I am getting this error:

TypeError: Car() takes no arguments.

class Car:
   def __rep__(self):
        return f'Car({self.name},{self.year_built},{self.model})'


c1 = Car('minicooper','1970','MX1')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your program is missing constructor and hence the error. Also do note that you are probably referring to __repr__ and not __rep__. You final code should look something like this -

class Car: 
    # In your code, this constructor was not defined and hence you were getting the error
    def __init__(self,name,year,model):
        self.name = name
        self.year_built = year
        self.model = model
    def __repr__(self):
        return f'Car({self.name},{self.year_built},{self.model})'

# The below statement requires a constructor to initialize the object
c1 = Car('minicooper','1970','MX1')

#
print(c1)

Output :

>>> Car(minicooper,1970,MX1)

The __init__ is used in python as constructor. It is used to initialize the object’s state. The task of constructors is to initialize(assign values) to the data members of the class when an object of class is created. So, when you pass the variables in your call - Car('minicooper','1970','MX1'), the constructor is called. You didn't had a constructor and hence you were getting the error message.

__repr__(object) is used to return a string containing a printable representation of an object. This will be used when you are trying to print the object. You had incorrectly mentioned it as __rep__ in your code. I have corrected it in the code above.

Hope this helps !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...