Python ошибка takes no arguments

Учу python по книжке «Укус питона». Там был код, похожий на мой (почти такой-же). Проблема в том, что когда я запускаю свой код, то он выдает ошибку:

Traceback (most recent call last):
  File "D:/Python/objvar.py", line 24, in <module>
    igor = humans("Игорь")
TypeError: humans() takes no arguments

Заранее благодарен, если скажите, где я ошибся/что неправильно написал. Вот код:

class humans:

    humans_count = 0

    def _init__(self, name):
        self.name = name
        print("В комнате есть {0}" .format(self.name))

        humans.humans_count += 1
    def __del__(self): #Выполняется при удалении (del)
        print("{0} вышел из комнаты" .format(self.name))

        human.humans_count -= 1

        if humans_count == 1:
            print("Остался один человек")
        elif humans == 0:
            print("В комнате не осталось людей")
    def count(self):
        print("В комнате {0} человек" .format(Humans.humans_count))

    count = staticmethod(count)

igor = humans("Игорь")
igor.count()
alex = humans("Алекс")
alex.count()

del alex
del igor

humans.count()

задан 12 апр 2020 в 2:03

Игорь Руденко's user avatar

Ошибка TypeError: humans() takes no arguments вызвана неправильным объявлением конструктора класса.

Функция-конструктор обязательно должна называться __init__, и никак иначе. У вас же она называется _init__.

Кроме того, в программе есть логические ошибки и ошибки с несуществующими переменными:

  • переменная Humans в методе count не существует;

  • метод count статическим быть не должен;

  • обращение к данным объекта реализуется не через название класса (human.humans_count), а через параметр метода self (self.humans_count)

ответ дан 12 апр 2020 в 2:17

Евгений's user avatar

ЕвгенийЕвгений

4,4872 золотых знака8 серебряных знаков28 бронзовых знаков

Не согласен с предыдущим оратором местами. Count вполне можно и нужно делать статическим методом. У вас просто напутано много — human вместо humans, например, и есть обращение к переменным вообще без указания объекта/класса. Я всё исправил:

class humans:

    humans_count = 0

    def __init__(self, name):
        self.name = name
        print("В комнате есть {0}" .format(self.name))
        humans.humans_count += 1

    def __del__(self): #Выполняется при удалении (del)
        print("{0} вышел из комнаты" .format(self.name))
        humans.humans_count -= 1
        if humans.humans_count == 1:
            print("Остался один человек")
        elif humans.humans_count == 0:
            print("В комнате не осталось людей")

    def count():
        print("В комнате {0} человек" .format(humans.humans_count))


igor = humans("Игорь")
humans.count()
alex = humans("Алекс")
humans.count()

del alex
del igor

humans.count()

Вывод программы:

В комнате есть Игорь
В комнате 1 человек
В комнате есть Алекс
В комнате 2 человек
Алекс вышел из комнаты
Остался один человек
Игорь вышел из комнаты
В комнате не осталось людей
В комнате 0 человек

ответ дан 12 апр 2020 в 7:40

CrazyElf's user avatar

CrazyElfCrazyElf

65.7k5 золотых знаков19 серебряных знаков50 бронзовых знаков

  1. Название класса пишется с большой буквы и не как иначе.
  2. Сейчас вы пишите название класса с humans, а потом исправляете на Hemans согласное Pep8, и вызов humans.humans_count += 1 уже не работает, это плохая практика нужно писать slef.humans_count += 1. Как правильно заметил человек выше.
  3. И в данном случае я не вижу смысла использовать статический метод так как статический метод работает только с переданными в него отдельно аргументами, а если по выпендриваться можно использовать класс метод.

ΝNL993's user avatar

ΝNL993

3,2962 золотых знака9 серебряных знаков26 бронзовых знаков

ответ дан 2 авг 2022 в 19:38

ScorpionEvil 777's user avatar

1

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

  • Pyinstaller ошибка при компиляции
  • Python вызов ошибки raise
  • Python ошибка invalid literal for int with base 10
  • Pyinstaller ошибка после компиляции
  • Python выдает ошибку синтаксиса