Ошибка takes 0 positional arguments but 1 was given

Что означает ошибка TypeError: something() takes 0 positional arguments but 1 was given

Что означает ошибка TypeError: something() takes 0 positional arguments but 1 was given

Это когда аргументы появляются там, где их быть не должно

Это когда аргументы появляются там, где их быть не должно

Ситуация: вы решили освоить мощь классов и попробовать ООП на Python. Делаете всё как по учебнику: сначала описываете класс, внутри него метод, а внутри метода — простую команду, которая пишет тестовое сообщение на экране:

# объявляем класс
class myClass():
    # внутри класса объявляем метод
    def myMethod():
        # внутри метода пишем команду, которую будет выполнять наш метод
        print('Это вызов метода внутри класса')

# создаём новый объект на основе класса
a = myClass()
# вызываем метод этого объекта
a.myMethod()

Кажется, что всё правильно, но при запуске появляется ошибка:

❌TypeError: myMethod() takes 0 positional arguments but 1 was given

Странно, ведь мы всё сделали всё как нужно.

Что это значит: Python обнаружил аргументы там, где их быть не должно. А раз аргументы есть и компилятор не знает, что с ними делать, то он останавливается и выдаёт эту ошибку.

Когда встречается: во всех случаях, когда мы указываем лишние аргументы или ставим их там, где они не нужны. Это необязательно будут ситуации из ООП — ошибка с аргументом может появиться в любой программе, где есть лишний аргумент.

Что делать с ошибкой TypeError: something() takes 0 positional arguments but 1 was given

Общее решение очевидно: нужно посмотреть на строку, на которую ругается Python, проверить в ней все аргументы и сверить их количество с тем, что должно быть по синтаксису. 

Вот простой случай: проверяем условие, и если всё сходится — выводим все названия ключей из словаря:

if choice == "5":
print("Решение найдено:")
for i in dictionary:
print(dictionary.keys(i))

Здесь будет такая же ошибка, потому что у keys() не может быть аргументов — он сразу выводит список всех ключей словаря. Достаточно написать так, чтобы ошибка ушла:

if choice == "5":
print("Решение найдено:")
for i in dictionary:
print(dictionary[i])

В нашем случае с ООП проблема чуть хитрее: Python ругается на строку a.myMethod(), у которой и так в описании нет никаких параметров. Но здесь дело в другом — вызов метода таким способом и есть ошибка. Объект почему-то не знает, что у него есть метод, который можно вызывать сам по себе, и воспринимает команду myMethod() как лишний аргумент.

Всё из-за того, что мы в описании метода не поставили в качестве аргумента ключевое слово self — оно как раз показывает, что этот метод можно вызывать снаружи. Добавим это, и ошибка исчезнет:

# объявляем класс
class myClass():
    # внутри класса объявляем метод
    def myMethod(self):
        # внутри метода пишем команду, которую будет выполнять наш метод
        print('Это вызов метода внутри класса')

# создаём новый объект на основе класса
a = myClass()
# вызываем метод этого объекта
a.myMethod()

Вёрстка:

Кирилл Климентьев

I got the same error:

TypeError: test() takes 0 positional arguments but 1 was given

When defining an instance method without self and I called it as shown below:

class Person:
          # ↓↓ Without "self"     
    def test(): 
        print("Test")

obj = Person()
obj.test() # Here

So, I put self to the instance method and called it:

class Person:
            # ↓↓ Put "self"     
    def test(self): 
        print("Test")

obj = Person()
obj.test() # Here

Then, the error was solved:

Test

In addition, even if defining an instance method with self, we cannot call it directly by class name as shown below:

class Person:
            # Here     
    def test(self): 
        print("Test")

Person.test() # Cannot call it directly by class name

Then, the error below occurs:

TypeError: test() missing 1 required positional argument: ‘self’

But, if defining an instance method without self, we can call it directly by class name as shown below:

class Person:
          # ↓↓ Without "self"     
    def test(): 
        print("Test")

Person.test() # Can call it directly by class name

Then, we can get the result below without any errors:

Test

In detail, I explain about instance method in my answer for What is an «instance method» in Python? and also explain about @staticmethod and @classmethod in my answer for @classmethod vs @staticmethod in Python.

In this article, we’ll learn how to fix the error “Takes 0 positional arguments but 1 was given”. Let’s get started!

Why does “Takes ‘0’ positional arguments but ‘1’ was given” error occur?

Let’s define the following sample function “add_numbers” which accepts two arguments num_1 and num_2.

Code example 1:

def add_numbers(num_1, num_2):
    sum = num_1 + num_2
    print('The sum of two numbers is: ', sum)

Now when we need to add two numbers, we only need to pass those numbers as arguments to the function. Take a look below:

Output:

>>> add_numbers(33, 23) # calling the function first time
>>> The sum of two numbers is: 56
>>> add_numbers(45, 45) # calling the function second time
>>> The sum of two numbers is: 90

Hence, from the output, we can see that calling the function as many times is much easier than performing raw addition. Let us perform another task of multiplying two numbers.

Code example 2:

def multiply(num_1, num_2):
    product= num_1 * num_2
    print('The product of two numbers is: ', product)

Output:

>>> multiply(4, 100) # calling the function first time
>>> The product of two numbers is: 400
>>> multiply(40, 60) # calling the function second time
>>> The product of two numbers is: 2400

Types of functions

There are two types of functions:

  1. Parameterized: Values to be placed inside the parenthesis. Generally is used for the high end applications.
  2. Non-parameterized: Empty parenthesis. Generally in use for basic processes.
Types Of Functions In Python 2
Types of functions in Python

When programmers work with parameters of a particular function they need to keep a track of some things in mind:

  1. The number of parameters the function holds.
  2. What each parameter is supposed to do.

When a programmer fails to consider these two points, the python interpreter raises errors. One of those is:

Traceback (most recent call last):
  File "c:UsersLenovoDesktopsample.py", line 8, in <module> 
    function(parameter)
TypeError: function() takes 0 positional arguments but 1 was given

This is the most common TypeError in Python. It occurs when the specified matching data type is not found for that particular piece of code.

Example: Takes 0 positional arguments but 1 was given.

Let us say, we define a function to divide two numbers. It is a non-parameterized function that takes input after calling.

Example 1:

def divide():
    num_1 = int(input('enter num_1: ' )) # taking input for num_1
    num_2 = int(input('enter num_2: ' )) # taking input for num_2
    
    div = num1/num2
    print('The division is: ', div)

divide(3)

Output:

Traceback (most recent call last):
  File "c:UsersLenovoDesktopsample.py", line 8, in <module>
    divide(3)
TypeError: divide() takes 0 positional arguments but 1 was given

In the above case, the divide() function requires two parameters. Both the parameters are mandatory and neither of them is positional. This is why, the function throws an error “takes 0 positional arguments, but 1 was given”

When we call divide() with one parameter the interpreter throws the error.

Example 2:

def add_numbers():
    num_1 = int(input('Enter number 1: '))
    num_2 = int(input('Enter number 2: '))  
    sum = num_1 + num_2
    print('The sum of two numbers is: ', sum)

add_numbers(45, 2) #  calling the function in python shell

Output:

Traceback (most recent call last):
  File "c:UsersLenovoDesktopsample.py", line 7, in <module>       
    add_numbers(45, 2)
TypeError: add_numbers() takes 0 positional arguments but 2 were given

As we know that the interpreter reads the code line by line it is scanning each line of code and throws the error. We get the same error as we give two positional arguments despite the function accepting nothing.

How to Fix “Takes ‘0’ positional arguments but ‘1’ was given” Error?

The error will display the function name where the error occurs. To fix the error:

  • Check what type of parameters the functions accepts
  • Find all the calls for that function and identify if any of the function call is incorrectly made
  • Fix the error by simply changing the function call in question

Conclusion

The topic of “takes 0 positional arguments but 1 was given” ends here. The concept is straightforward. I hope you were able to fix the error in your code. IF you have any questions, drop us a line and we’ll help you out.

The takes 0 positional arguments but 1 was given error and it’s variations like takes 0 positional arguments but 1 was given kwargs will always pop up when the Python interpreter thinks that you are passing an argument to a function or method that accepts zero arguments.takes 0 positional arguments but 1 was given

However, the situation may vary based on your logic and coding script. But this post will help you sort out the problematic code block within minutes and help you correct your mistake to remove the error.

So, sit back, take a deep breath, and read this guide to gain awareness regarding the stated error and discover different ways to solve it.

Contents

  • Takes 0 Positional Arguments But 1 Was Given: Causes Described
    • – Your Class Method Is Being Supplied With Self Automatically
    • – You Have Used def To Create a Python Class
    • – Functions With the Same Names But Different Definitions
  • Takes 0 Positional Arguments But 1 Was Given: Fixing Techniques
    • – Add self To the Method Definition
    • – Declare It a Static Method Explicitly
    • – Use the Class Keyword To Create a Python Class
    • – Get Right With Your Functions
  • FAQs
    • 1. What Does the Error Takes 1 Positional Argument But 2 Were Given Mean?
    • 2. Is It Important To Pass the Positional Arguments in the Specified Order?
    • 3. Which Should Come First While Using Positional and Keyword Arguments?
    • 4. Which Functions Don’t Accept Any Arguments?
    • 5. How To Make Your Function Accept Variable Number of Arguments?
  • Conclusion

Takes 0 Positional Arguments But 1 Was Given: Causes Described

The ‘takes 0 positional arguments but 1 was given python’ error is caused by the automatic passage of the “self” argument to your class method. Plus, using the def keyword to create a class, or implementing function recursion with differently defined functions can lead to the error in the title.

– Your Class Method Is Being Supplied With Self Automatically

If you have a method that doesn’t accept any arguments and you call it on your class with empty parentheses, Python will pass self to it automatically. This automatic passage of the self to a method that doesn’t expect it will lead you to the given error or its variations like takes 0 positional arguments but 2 was given.Takes 0 Positional Arguments But 1 Was Given Causes

For example, you are calling a method “produceCode()” on your class. The method doesn’t ask for any arguments. Thus, you haven’t passed any arguments to it and have kept the parentheses empty. According to this, you haven’t made any blunder related to the arguments.

Still, you’ll get the ‘takes 0 positional arguments but 1 was given pytest’ error on your PC. The reason behind this would be Python, which sends an argument to the produceCode() method automatically.

You can look at the following erroneous code snippet to better understand errors like __init__() takes 0 positional arguments but 1 was given.

def produceCode():

Pass

produceCode() # Python will pass self to this method

– You Have Used def To Create a Python Class

Using the def keyword to create a Python class will confuse Python about its identity. Python will assume your class to be a function and think that the value passed while object creation to the class constructor is a function argument. Consequently, you’ll get the ‘takes 0 positional arguments but 1 was given class’ error.

Imagine that you have mistakenly used the def keyword to create the student class. The class constructor initializes the “name” property. Therefore, you pass the name to the class constructor while creating an object of the student class. Here, as you’ve used the def keyword, Python will interpret your class as a function.

Moreover, the empty parentheses following “def student” will make it believe that the function doesn’t accept any arguments. Therefore, the error will appear during class instantiation due to the interpreter’s confusion.

You can look at the piece of code attached below for a better understanding.

def student():

def __init__(self, name):

self.name = name

a = student(name)

– Functions With the Same Names But Different Definitions

If your coding script contains two functions with the same name, but different definitions and the non-parameterized function calls its twin but parameterized function inside its body, you’ll see the stated error on your computer. This way of naming and calling the functions causes recursion.

Although function recursion is a Python feature, the difference in the parameters generates the issue. For example, you have a non-parameterized function “inform()” and a parameterized function “inform(x).” Now, if you call the inform(x) function inside the body of the inform() function, Python will issue a complaint that the inform() takes 0 positional arguments, but you passed 1 to it.

The code block attached below will clarify your doubts and let you have a closer view of the problem.

# a parameterized function

def inform(x):

# add function body

# a non-parameterized function

def inform():

# calling a parameterized function inside a

non-parameterized function with the same name

inform(x)

# calling the non-parameterized function

inform()

Takes 0 Positional Arguments But 1 Was Given: Fixing Techniques

You can fix the takes 0 positional arguments but 1 was given error by passing a self parameter to the class method’s definition, or using the @staticmethod annotation. Moreover, creating a Python class using the class keyword, or implementing the function recursion correctly can help fix the error.

– Add self To the Method Definition

You should add a self parameter to the method definition to ensure that no issue will occur when Python sends a self argument during the call to the same method. As the “self” parameter will be a part of the method definition, the “self” argument won’t cause the error.

Talking about the previous example, you should pass “self” to the definition of the produceCode() method to resolve the said error. The altered method definition can be seen below.

def produceCode(self)

pass

– Declare It a Static Method Explicitly

You can declare your method as a static method by using the @staticmethod annotation to tell Python that it doesn’t need to pass self to the same. Eventually, if the auto-generated “self” argument doesn’t enter the method’s parentheses, you’ll be saved from the error.

So, a simple step of adding a @staticmethod annotation above the method definition will be sufficient to push away the said error. Considering the same produceCode() method, here is how you can declare it a static method.

@staticmethod

def produceCode()

pass

Note that this solution is an alternative technique to the one involving passing a “self” parameter to the method definition. You can either pass the self parameter or make the method static to get an error-free output.

– Use the Class Keyword To Create a Python Class

You must always create a Python class using the class keyword to avoid any misassumptions and keep a distance from the stated error. For clarification, note that the class keyword is used for creating a class, while the def keyword is used for defining a function.Takes 0 Positional Arguments But 1 Was Given Fixes

Always remember that mixing up the two keywords, even mistakenly, can be disastrous to your code. The correct way to create an employee class has been depicted below.

class employee():

def __init__(self, desig):

self.desig = desig

b = employee(desig)

– Get Right With Your Functions

The function recursion deals with calling a particular function inside the same function. Also, you should know that two functions with the same name but different definitions aren’t the same. Thus, avoiding function recursion with differently defined functions can help eliminate the error.

If you talk about the inform() and inform(x) functions again, you should stop calling the parameterized inform(x) function inside the non-parameterized inform() function to get rid of the error. However, you can still call inform() inside inform() and inform(x) inside inform(x), which is the correct form of function recursion.

You can see the function recursion sample code below for clarity.

def inform(x):

inform(x)

def inform():

inform()

inform()

inform(x)

FAQs

1. What Does the Error Takes 1 Positional Argument But 2 Were Given Mean?

The TypeError: takes 1 positional argument but 2 were given means that you have created a class and added a method to the same, but you haven’t added the self parameter to the method definition. Moreover, Python has sent an additional “self” argument to the method while calling it.

2. Is It Important To Pass the Positional Arguments in the Specified Order?

Yes, it is important to pass the positional arguments in the specified order to get the desired results from your function. The term positional refers to the argument’s position, which must never be switched with the other argument’s position for the proper working of the function.

3. Which Should Come First While Using Positional and Keyword Arguments?

The positional arguments should come first while using a combo of positional and keyword arguments. This rule will work because Python depends on the positions of the positional arguments within the function call to process them effectively and generate the desired output.

4. Which Functions Don’t Accept Any Arguments?

The functions printing statements or performing calculations on a set of values might not accept any arguments. It indicates that they don’t need any additional values or data to perform their tasks and are self-sufficient. All you have to do is to call them with empty parentheses in your program.

5. How To Make Your Function Accept Variable Number of Arguments?

You can use the asterisk “*” operator followed by a variable name in the function definition to make your function accept a variable number of arguments. The given symbol informs Python that the function can take up any number of arguments and they all should be added into a tuple.

Conclusion

The error statement conveying a complaint regarding the passage of the unnecessary arguments will usually occur when Python sends the argument, even without asking you. However, you can perform a few tricks to either accept the automated argument gracefully and stop it from entering the method’s parentheses. For a quick recap of the post, you can read the below listicle.

  • You must add a self parameter to the method’s definition to remove the error permanently.
  • Adding the @staticmethod annotation above the method definition can help resolve the error.
  • Being thoughtful about the usage of the def and class keywords will be beneficial in avoiding the error.
  • You should always implement function recursion with the same method.

Keeping an eye on your method or function arguments is a great tip to avoid having such errors on your computer.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

When working with Python functions and classes, you might see the following error:

TypeError: function() takes 0 positional arguments but 1 was given

This error usually occurs when you call and pass an argument to a function that accepts 0 arguments.

There are two possible reasons why this error happens:

  1. Your function accepts 0 arguments, but you pass it an argument when calling
  2. You specify a class method without the self parameter

The following tutorial shows how to fix this error in both scenarios.

Note: arguments are called parameters when you specify them in the function header.

1. The function accepts 0 arguments

Suppose you have a function named greet() that has no parameter.

You then called the function and pass it an argument as shown below:

def greet():
    print("Hello World!")

greet("John")  # ❌

Python tries to send the argument John to the greet() function, but the function takes 0 arguments so the error occurs:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    greet("John")
TypeError: greet() takes 0 positional arguments but 1 was given

To fix this error, you need to remove the argument when you call the function, or you can specify parameters for the function as follows:

# 1. Remove the argument from the function call
def greet():
    print("Hello World!")

greet()  # Hello World!

# 2. Add parameter to the function
def greet(name):
    print(f"Hello {name}!")

greet("John")  # Hello John!

You’ll also get this error when you pass too many arguments to a function.

In the code below, the greet() function takes one argument but you give it two:

def greet(name):
    print(f"Hello {name}!")

greet("John", 29)
# TypeError: greet() takes 1 positional argument but 2 were given

When the function takes one argument, you need to pass it one argument.

2. A class method without the self parameter

This error also happens when you specify a class method without the self parameter.

Suppose you have the create a class named Human that has the following definition:

class Human:
    def talk():
        print("Talking")

Next, you instantiate an object from the class and call the talk() method:

person = Human()
person.talk()  # ❌

Output:

TypeError: Human.talk() takes 0 positional arguments but 1 was given

This error occurs because Python internally passes the class instance (the object itself) whenever you call a method of that class.

To resolve this error, you need to specify self as the parameter of all methods in your class even when you didn’t need it:

class Human:
    def talk(self):
        print("Talking")

person = Human()
person.talk()  # Talking

This time, we didn’t get any error because the talk() method accepts the self argument that gets passed automatically when you call it.

To conclude, the error TypeError: method() takes 0 positional arguments but 1 was given occurs when you pass one argument to a function that doesn’t take any.

You can fix this error by specifying the parameters required by the function, or you can remove the argument when calling that function.

I hope this tutorial is helpful. Enjoy coding! 👍

Понравилась статья? Поделить с друзьями:
  • Ошибка system will shut down
  • Ошибка table was not locked with lock tables
  • Ошибка system volume information что это
  • Ошибка table or view does not exist
  • Ошибка system thread not handled windows 10 как исправить