Python init takes no arguments

Fix Python TypeError: Object() takes no arguments

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:

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:

  • 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:

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:

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:

 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. 👍

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Источник

How to Solve Python TypeError: object() 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?

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!

Share this:

Источник

Python init takes no arguments

Last updated: Feb 2, 2023
Reading time · 3 min

banner

# TypeError: Class() takes no arguments in Python

The Python «TypeError: Class() takes no arguments» occurs when we forget to define an __init__() method in a class but provide arguments when instantiating it.

To solve the error, make sure to define the __init__() (two underscores on each side) method in the class.

python typeerror class takes no arguments

Copied!
Traceback (most recent call last): File "/home/borislav/Desktop/bobbyhadz_python/main.py", line 62, in module> emp = Employee('Bobby Hadz', 100) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Class() takes no arguments TypeError: Object() takes no arguments

Here is an example of how the error occurs.

Copied!
class Employee(): def get_salary(self): return self.salary # ⛔️ TypeError: Employee() takes no arguments emp = Employee('Bobby Hadz', 100) print(emp)

We haven’t defined an _ _ init _ _ () method but are passing arguments to the class.

When a class is instantiated, its __init__() method gets called with the supplied arguments.

# Define an _ _ init _ _ method to solve the error

To solve the error, make sure to define an __init__() method or correct your spelling if your class already has one.

Copied!
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def get_salary(self): return self.salary emp = Employee('Bobby Hadz', 100) print(emp.name) # 👉️ Bobby Hadz print(emp.get_salary()) # 👉️ 100

define init method to solve the error

Make sure your indentation is correct and you haven’t misspelled __init__ (two underscores on each side).

Copied!
def __init__(self, name, salary): # ✅ correct def _init_(self, name, salary): # ⛔️ incorrect def __init(self, name, salary)__: # ⛔️ incorrect

If you mistype the __init__ method in the class’s definition, it won’t get invoked when the class is instantiated.

When a class defines the __init__() method, the method is invoked when an instance is created.

The following line calls the __init__() method of the class.

Copied!
emp = Employee('Bobby Hadz', 100)

If you pass arguments when instantiating a class, the arguments are passed on to the __init__() method.

The __init__() method isn’t supposed to return anything.

Note that the first argument the __init__() method takes is self.

Copied!
def __init__(self, name, salary): self.name = name self.salary = salary

You could name this argument anything because the name self has no special meaning in Python.

self represents an instance of the class, so when we assign a variable as self.my_var = ‘some value’ , we are declaring an instance variable — a variable unique to each instance.

When defining the __init__ method, make sure you have indented the code block consistently.

Copied!
class Employee(): def __init__(self, name, salary): # ⛔️ forgot to indent method self.name = name self.salary = salary

If the method isn’t indented correctly, you will either get an error or the method won’t run when you instantiate the class.

Note that unlike other methods, the __init__ method isn’t supposed to return anything.

The method is used to assign properties to the newly created class instance.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Python load png image
Оцените статью