TypeError: Car() takes no arguments

Question:

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')
Asked By: Gyan

||

Answers:

class Car:
   # Constructor
   def __init__(self, name, year_built, model):
       self.name = name
       self.year_built = year_built
       self.model = model

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


c1 = Car('minicooper','1970','MX1')

I hope this helps.

Answered By: Harshit

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 !

Answered By: Abhishek Bhagate
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.