Python ошибка takes no arguments

In Python, we use __init__() as a constructor function when creating an object of a class. This function allows you to pass arguments to a class object. If you misspell the __init__ function, you will encounter the error: TypeError: object() takes no arguments.

To solve this error, you need to ensure that you spell the __init__ function with two underscores on either side of init, and you use correct indentation throughout your program.

This tutorial will go through the error in detail, and we will go through an example to learn how to solve it.


Table of contents

  • TypeError: object() takes no arguments
    • What is a TypeError?
    • What is __init__ in Python?
  • Example: Creating a Class in Python
    • Solution
  • Summary

TypeError: object() takes no arguments

What is a TypeError?

TypeError occurs in Python when you perform an illegal operation for a specific data type. For example, if you try to index a floating-point number, you will raise the error: “TypeError: ‘float’ object is not subscriptable“. The part object() takes no arguments tells us that an object of the class we want to use does not accept any arguments.

What is __init__ in Python?

The __init__ method is similar to constructors in C++ and Java. We use the __init__ method to initialize the state of an object. The syntax of the __init__() function is:

def __init__(self, object_parameters):

    # Initialize the object

The function takes in self and the object parameters as input and assigns values to the data members of the class when we create an object of the class. Object parameters are the state variables that define the object. The self is a reserved keyword in Python, which represents the instance of the class.

The ‘self‘ keyword enables easy access to the class methods and parameters by other methods within the class.

When you create an object of a class, you want to put any code you want to execute at the time of object creation in the __init__ method. Let’s look at an example of a class with the __init__ method:

class Footballer

    def __init__(self, name)

        self.name = name
    

The __init__ method assigns the value for the self.name variable in the Footballer class. We can reference this variable in any following method in the class.

The syntax and spelling of the __init__ method must be correct; otherwise, you will not be able to pass arguments when declaring an object of a class. You must use two underscores on either side of init.

The “TypeError: object() takes no arguments” error can also occur due to incorrect indentation. You must use either all white spaces or all tabs to indent your code blocks in your program. For further reading on correct indentation, go to the following article: How to Solve Python IndentationError: unindent does not match any outer indentation level.

Example: Creating a Class in Python

Let’s look at an example where we create a program that stores the information of different countries. We will start by defining the class. Classes are a blueprint or a set of instructions to build a specific type of object.

class Country:

    def _init_(self, name, capital, language):

        self.name = name

        self.capital = capital

        self.language = language

    def show_main_language(self):

        print('The official language of {} is {}.'.format(self.name, self.language))

The Country class has two methods. Firstly, an __init__ method defines all of the values that objects of the class can store. The second method prints the official language of a country.

Next, we will attempt to create an object of the Country class.

bulgaria = Country("Bulgaria", "Sofia", "Bulgarian")

The above code creates an object for the country Bulgaria. Now we have an object of the class, and we can attempt to call the show_main_language() method to get the official language of Bulgaria.

bulgarian.show_main_language()

Let’s run the code to get the outcome:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
bulgaria = Country("Bulgaria", "Sofia", "Bulgarian")

TypeError: Country() takes no arguments

We throw the error because we specify values to assign to the variables inside the object, but this is only possible with a correct __init__ method definition. If there is no __init__ method present in the class, the Python interpreter does not know what to do with the values you pass as arguments during object creation.

Solution

In the example code, we declared an _init_ method, where there is one underscore on each side. The correct syntax for the constructor needs two underscores on each side. Let’s look at the revised code:

class Country:
    def __init__(self, name, capital, language):
        self.name = name
        self.capital = capital
        self.language = language

    def show_main_language(self):

        print('The official language of {} is {}.'.format(self.name, self.language))

We have a valid __init__ method in the Country class. We can create an object and call the show_main_language() method.

bulgaria = Country("Bulgaria", "Sofia", "Bulgarian")

Let’s run the program to get the result:

The official language of Bulgaria is Bulgarian.

The program successfully prints the official language of Bulgaria to the console.

Summary

Congratulations on reading to the end of this tutorial! You will encounter the error “TypeError: object() takes no arguments” when you do not declare a constructor method called __init__ in a class that accepts arguments.

To solve this error, ensure that an __init__() method is present and has the correct spelling. The method must have two underscores on either side for Python to interpret it as the constructor method.

The error can also occur if you are not using a consistent indentation method in the class that is causing the error.

For further reading on passing arguments in Python go to the article: How to Solve Python SyntaxError: positional argument follows keyword argument.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

The arguments a class object accepts are passed through a function called __init__(). If you misspell this function in your class declaration, you’ll encounter a “TypeError: object() takes no arguments” error when you run your code.

In this guide, we talk about what this error means and why you may encounter it. We’ll walk through an example of this error to help you figure out how to fix it.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

TypeError: object() takes no arguments

Objects of a class can optionally accept arguments. These arguments are used to set values within an object. Consider the following code:

class Employee:
	def __init__(self, name)
		self.name = name

The __init__method lets us assign a value for the “self.name” variable in our class. We can reference this variable in any method in our class.

The __init__ method is a special method. It is often called a constructor. The constructor method must be spelled correctly, otherwise you cannot pass any arguments into a statement where you declare an object of a class.

For reference, the __init__ method is spelled as:

Two underscores, followed by “init”, followed by two underscores.

The “TypeError: object() takes no arguments” error can also be caused by improper indentation. If you have spelled the __init__ method correctly, check to make sure you use consistent spaces and tabs in your class.

An Example Scenario

We’re going to create a program that tracks information about a product in an electronics store. To start, define a class. This class serves as the blueprint for our products:

class Product:
	def _init_(self, name, price, brand):
		self.name = name
		self.price = price
		self.brand = brand

	def show_price(self):
		print("The price of {} is ${}.".format(self.name, self.price))

Our class contains two methods. The first method is our constructor. This method defines all the values that objects of our class can store. The second method lets us view the price of a product.

Next, we’re going to create an object of our class:

george_foreman = Product("Fit Medium Health Grill", 39.99, "George Foreman")

This code creates an object for a George Foreman grill that is on sale at the electronics store. Next, we’re going to call our show_price() method so that we can view the price of this product:

george_foreman.show_price()

Let’s run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
	george_foreman = Product("Fit Medium Health Grill", 39.99, "George Foreman")
TypeError: Product() takes no arguments

Our code returns an error message.

The Solution

To assign initial values to variables inside an object, you have to specify the values of those variables as arguments in the statement where an object is declared.

This only works if there is a valid __init__ method in an object. Otherwise, Python does not know how to treat the values you have specified as arguments. Without a special __init__ method, Python would not know which method should process the arguments.

In our code, we have declared an _init_ method (with one underscore on each side):

class Product:
	def _init_(self, name, price, brand):

This is not treated the same as __init__. To solve this error, we have to rename this method so that it uses the right syntax:

class Product:
	def __init__(self, name, price, brand):
		self.name = name
		self.price = price
		self.brand = brand

We’ve renamed our method to __init__. Let’s run our code and see if it works:

The price of Fit Medium Health Grill is $39.99.

Our code successfully tells us the price of the George Foreman grill.

TypeError: this constructor takes no arguments

The “TypeError: object() takes no arguments” error appears as “TypeError: this constructor takes no arguments” in Python 2.x.

This message tells us that we have made a mistake in defining our constructor. To solve this problem, make sure that you spell the __init__() method correctly and that you use the correct indentation in the class that is causing the error.

Conclusion

The “TypeError: object() takes no arguments” error is raised when you do not declare a method called __init__ in a class that accepts arguments.

To solve this error, double-check your code to ensure that __init__() is spelled correctly. The method should have two underscores on either side of the word “init”.

Now you’re ready to fix this common Python error like a professional!

Допустим, есть некий класс А. Он был создан с целью демонстрации метода __call__.

class A(object):
	def __int__(self, x, y):
		self.x=x+y
	def __call(self,x,y):
		return x+y

a=A(1,2)
a(1,2)

Error
Traceback (most recent call last):
File «/home/…/PycharmProjects/Curses/OOP.py», line 8, in
a=A(1,2)
TypeError: A() takes no arguments

Не понимаю причин возникновения этой ошибки.

TypeError: Object() takes no arguments error occurs when you pass one or more arguments to instantiate an object from a class that has no __init__() method.

When initializing a Python object from a class, you can pass a number of arguments into the object by defining the __init__() method.

The __init__() method is the constructor method that will be run when you create a new object.

This article will show you an example that causes this error and how to fix it.

How to reproduce this error

Usually, you get this error when you try to instantiate an object from a class without an __init__() method.

Suppose you have a class as follows:

class Human:
    def walk():
        print("Walking")


person = Human("Nathan")  # ❌

The Human class in the example only has walk() method, but I instantiated a new person object and passed one string argument to it.

As a result, Python responds with this error message:

Traceback (most recent call last):
  File ...
    person = Human("Nathan")
TypeError: Human() takes no arguments

You might see the error message worded a bit differently in other versions of Python, such as:

  • TypeError: this constructor takes no arguments
  • TypeError: object() takes no parameters
  • TypeError: class() takes no arguments

But the point of these errors is the same: You’re passing arguments to instantiate an object from a class that has no __init__() method.

Alright, now that you understand why this error occurs, let’s see how you can fix it.

How to Fix TypeError: Object() takes no arguments

To resolve this error, you need to make sure that the __init__() method is defined in your class.

The __init__() method must be defined correctly as shown below:

class Human:
    def __init__(self, name):
        self.name = name

    def walk():
        print("Walking")


person = Human("Nathan")  # ✅

print(person.name)  # Nathan

Please note the indentation and the typings of the __init__() method carefully.

If you mistyped the method as _init_ with a single underscore, Python doesn’t consider it to be a constructor method, so you’ll get the same error.

The following shows a few common typos when defining the __init__() method:

init:
_init_:
init():
_init_():
__init():
__int__ 

The constructor method in a Python class must be exactly named as __init__() with two underscores. Any slight mistyping will cause the error.

You also need to define the first argument as self, or you will get the error message init takes 1 positional argument but 2 were given

The last thing you need to check is the indentation of the __init__() method.

Make sure that the method is indented by one tab, followed by the function body in two tabs.

Wrong indentation will make Python unable to find this method. The following example has no indent when defining the method:

class Human:
def __init__(self, name):  # ❌
    self.name = name

Once you have the __init__() method defined in your class, this error should be resolved.

Conclusion

Python shows TypeError: Object() takes no arguments when you instantiate an object from a class that doesn’t have an __init__() method.

To fix this error, you need to check your class definition and make sure that the __init__() method is typed and indented correctly.

Great work solving this error! I’ll see you again in other articles. 👍

In Python, we use the class keyword to create a blueprint for an object. And inside the class, we can define a special method

__init__(self)

which is the constructor of the class, and get automatically called when we create the class object. If we misspell, forget, or define the __init__() method with no argument, and create a class object by specifying the initial value. We will encounter the error

TypeError: ClassName() takes no arguments

Error.

In this Python guide, we will discuss the

TypeError: ClassName() takes no arguments

Error in Detail and see the different scenarios when you may encounter this error in your Python program.



Let’s


get started with the error statement


Python Error: TypeError: ClassName() takes no arguments

The Error statement

TypeError: ClassName() takes no arguments

can be divided into two parts,

Exception Type (

TypeError

)

and

Error Message (

ClassName() takes no arguments

).


1. TypeError

TypeError is a standard Python exception. It is raised in a Python program when we perform an invalid operation or function on a Python object. For example, passing argument value to a function or method that accepts no arguments will raise the TypeError with a specific Error Message.


2. ClassName() takes no arguments


ClassName() takes no arguments

is the Error message telling us that the class ClassName()

__init__()

method does not accept any argument value. When we initialize an object for a class, the

__init__()

method gets invoked automatically. If we have defined some parameters for the

__init__()

method in the class definition, we can pass argument values for those parameters during object initialization.

This Error generally occurs in a Python program when we create an object for a class and pass an argument value to the

__init__()

method where the

__init__()

method is not defined or accepts no argument.


Example Scenario

There could be two scenarios where you may encounter this error.

  1. Forget to define a

    __init__(self)

    method and create an object by passing arguments.
  2. Misspelled the

    __init__(self)

    method.


Example 1 (Forget to define __init__(self) method)



__init__()


is a special method. It is the constructor for the class and gets called when we initialize an instance or object for the Class. It is not necessary to define the

__init__()

method for a class, but if we wish to initialize some initial values to a class object, there we need to specify the

__init__()

method.

If we forget to define the

__init__()

method and try to initialize the class object with some argument values we will receive the

TypeError: ClassName() takes no arguments

Error.


Example 1

# create a class
class Student:
    # forget to define the __init__() method

    def show_marks(self):
        print(f"Total Marks of {self.name} are {self.marks}")

    def show_details(self):
        print("Name: ", self.name)
        print("Age: ", self.age)
        print("Grade: ", self.grade)
        print("Total Marks: ", self.marks)

#
name, age , grade, marks = ["Rahul Kumar", 17, "11th", 893]

# create an object
rahul = Student(name, age, grade, marks)


Output

Traceback (most recent call last):
  File "main.py", line 19, in 
    rahul = Student(name, age, grade, marks)
TypeError: Student() takes no arguments


Break the code

In this example, we are getting this error because, at object creation, we are passing 4 arguments value

name, age, grade, marks

to the

Student()

class, which is supposed to accept by the

__init__()

method.

By default, every time we define a class and create its object, Python automatically creates the

__init__()

method for that object. But that automatically created

__init__(self)

method does not accept any argument value. So if we want to initialize some initial values to object properties, we need to define the

__init__()

method in our class and specify the parameters. So it can accept all the argument values assigned during the object creation.


Solution

To solve the above problem, all we need to do is define the __init__() method for the class Student and define the 4 parameters for 4 argument values name, age, grade, and marks.

# create a class
class Student:
    # define the __init__() method
    def __init__(self, name, age, grade, marks):
        self.name = name
        self.age = age
        self.grade = grade
        self.marks = marks

    def show_marks(self):
        print(f"Total Marks of {self.name} are {self.marks}")

    def show_details(self):
        print("Name: ", self.name)
        print("Age: ", self.age)
        print("Grade: ", self.grade)
        print("Total Marks: ", self.marks)

#
name, age , grade, marks = ["Rahul Kumar", 17, "11th", 893]

# create an object
rahul = Student(name, age, grade, marks)

rahul.show_details()


Example 2 (Misspelt the __init__(self) method)

The method calling is similar to the function call. The same goes for the invoking of the

__init__()

method. As we do not call the

__init__()

method explicitly, it gets automatically called when we initialize the class object. Here the thing to keep in mind is that the

__init__()

is a reserved method, and when we use it in our class, we are just overriding the default __init__() method.

If during defining a __init__() method if we misspelled it, that method will be treated as a completely different method, and it will be assumed that the class has no __init__() method.


Example 2

# create a class
class Student:
    # misspell the __init__() method
    def __inti__(self, name, age, grade, marks):
        self.name = name
        self.age = age
        self.grade = grade
        self.marks = marks

    def show_marks(self):
        print(f"Total Marks of {self.name} are {self.marks}")

    def show_details(self):
        print("Name: ", self.name)
        print("Age: ", self.age)
        print("Grade: ", self.grade)
        print("Total Marks: ", self.marks)

#
name, age , grade, marks = ["Rahul Kumar", 17, "11th", 893]

# initialize an object
rahul = Student(name, age, grade, marks)

rahul.show_details()


Output

Traceback (most recent call last):
    File "main.py", line 25, in <module>
        rahul = Student(name, age, grade, marks)
TypeError: Student() takes no arguments


Break the code

In this example, we are getting the same error statement as we are receiving in the above example. If we analyze the code carefully, we will conclude that the core reason for this error is the same for both of the examples (Example 1 and Example 2).

Even in this example, there is no

__init__()

method that is supposed to invoke and accept the argument sent by the object during object initialization. Although the mistake is completely different here, we have tried to define the

__init__()

method, but we misspelled it.


Solution

To solve the above example, all we need to do is correct the spelling of

__init__()

method. Becaue Python is a case-sensitive programming language.

# create a class
class Student:
    # correct the __init__() method
    def __init__(self, name, age, grade, marks):
        self.name = name
        self.age = age
        self.grade = grade
        self.marks = marks

    def show_marks(self):
        print(f"Total Marks of {self.name} are {self.marks}")

    def show_details(self):
        print("Name: ", self.name)
        print("Age: ", self.age)
        print("Grade: ", self.grade)
        print("Total Marks: ", self.marks)

#
name, age , grade, marks = ["Rahul Kumar", 17, "11th", 893]

# initialize an object
rahul = Student(name, age, grade, marks)

rahul.show_details()


Output

Name: Rahul Kumar
Age: 17
Grade: 11th
Total Marks: 893


Conclusion

The Python Error «TypeError: Name() takes no arguments» is raised when we forget to define the __init__() method or misspell it, and we try to pass some argument values to the init method during object initialization. It is not necessary that if you do not define or misspell the

__init__()

method and you will encounter this error. You will only encounter this error when you pass some initial argument values to the object during object creation, and there is no __init__() method defined in the class that can accept all those arguments.

If you are getting this error in your Python program, you can share your code in the comment section. We will try to help you in debugging.


People are also reading:

  • Python typeerror: ‘str’ object is not callable Solution

  • How to Convert Python Files into Executables Standalone File?

  • Python TypeError: ‘method’ object is not subscriptable Solution

  • File I/O in Python

  • Python ValueError: invalid literal for int() with base 10: Solution

  • Move File in Python: A Complete Guide

  • Python TypeError: ‘function’ object is not subscriptable Solution

  • Read File in Python

  • Python SyntaxError: unexpected EOF while parsing Solution

  • How to Download Files in Python?

Понравилась статья? Поделить с друзьями:
  • Python ошибка int object is not callable
  • Python ошибка dataframe object is not callable
  • Python ошибка api ms win
  • Python обработка ошибок и исключений
  • Python обработка ошибок в цикле