Меню

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()

Вёрстка:

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

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.

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.

    Python Tutorials

  • Python Comments
  • Python Console Operations
  • Python Conditional Statements
  • Python Loop Statements
  • Python Enum
  • Python Operators
  • Python Functions
  • Python Builtin Functions
  • Python Type Conversion
  • Python Classes and Objects
  • Python Math Functions

The error says that as per the definition of method, it accepts no arguments, but we provided an an argument.

Recreate Python TypeError

An example class definition that could recreate this error is given below.

Python Program

class Laptop:
	def details():
		print('Hello! I am a laptop.')

laptop1 = Laptop()
laptop1.details()

Output

Traceback (most recent call last):
  File "example1.py", line 6, in <module>
    laptop1.details()
TypeError: details() takes 0 positional arguments but 1 was given

You might be wondering that you have not passed any arguments when you called details() method on the laptop1 object. But, why Python is throwing the TypeError?

Here is why. By default, if the method is not a static python method, then implicitly the object (self) is passed as argument. So, when you called laptop1.details(), it is actually being called as laptop1.details(laptop1).

Solution for TypeError

And to comply this inbuilt behavior, we need to provide an argument in the definition of details() method as shown below:

Python Program

class Laptop:
	def details(self):
		print('Hello! I am a laptop.')

laptop1 = Laptop()
laptop1.details()

Output

Hello! I am a laptop.

Also, there is another way, if the method is meant to be a static method. You can tell Python Interpreter that this method is a static method using @staticmethod as shown below.

Python Program

class Laptop:
	@staticmethod
	def details():
		print('Hello! I am a laptop.')

laptop1 = Laptop()
laptop1.details()

Output

Hello! I am a laptop.

Summary

In this tutorial of Python Examples, we have learned to solve the TypeError: method() takes 0 positional arguments but 1 was given, with the help of example programs.


from tkinter import *

root = Tk()
root.title('Clicer')
root.update()
coin = 1
coins = 0
ten = 10
XX2 = 1
clock_by = 2
clock_buust = 1
while_time = 300
root.geometry('480x340')
root.resizable(width=False, height=False)
def msg():
    global coin
    global coins
    global text
    coins += int(coin * XX2)
    frame['text'] = coins
        
def Shop_Open():   
    def X2():
        global coins
        global ten
        global XX2
        if coins >= ten:
            coins = coins - ten
            ten += int(ten * 2)
            XX2 += 1 * 2
            frame['text'] = coins
            Price['text'] = ten
        else:
            Price['text'] = ten
            
    def Time_by(clock=0):
        by_panelvar.set(clock)
        global coins
        global clock_by
        global clock_buust
        if coins >= clock_by:
            coins = coins - clock_by   
            clock_by*=2       
            root.after(1000, lambda: Time_by(clock+1), print(clock))           
            frame['text'] = coins
            frame_1['text'] = clock
            #Check Shop.
            Price_sec['text'] = clock_by
        else:
            Price_sec['text'] = clock_by
    
    by_panelvar = StringVar()       
    by_panelvar.set(u'original value')           
    by_panel = Tk()
    by_panel.title('Shop')
    by_panel.geometry('280x140')
    by_panel.resizable(width=False, height=False)
    by_panel.update()
    Shop_panel = PanedWindow(by_panel, orient=HORIZONTAL)
    Shop_panel.grid()
    Price = Label(by_panel, width=10, height=1)
    Price.grid()
    By_x2 = Button(by_panel, text='By_x3',bg='red', command=X2)
    By_x2.place(x=5, y=16)
    Price_sec = Label(by_panel, width=10, height=1)
    Price_sec.place(x=0, y=40)
    By_1sec = Button(by_panel, text='1_in_sec', bg='orange', command=Time_by )
    By_1sec.place(x=5, y=56)
    by_panel.mainloop()
    
        
frame = StringVar()   
frame = Frame()
frame.pack()
frame.update()
frame = Label(frame, width=30, height=2, bg='black', fg='white')
frame_1 = Label(width=20, height=2, bg='green', fg='white')
frame_1.place(x=340, y=0)
    
# button_image = PhotoImage(file='button.png')    """image=button_image,"""
    
top = Frame()
top.pack()
top.update()
Clisc_buttob = Button(top, text='clic', width=200, height=200,
                        command=msg, overrelief=SUNKEN)
Clisc_buttob.pack(side=BOTTOM)

Shop_button = Button(text='Shop', command=Shop_Open)
Shop_button.place(x=0)

frame.pack()
root.mainloop()

Dung Do Tien
Sep 05 2021
619

Hi guys. 

I just recently started coding at my school and am learning to use Python. And I created an object class CustomerInfo as below:

class CustomerInfo:
    def __init__ ():
        self.name = name
        self.order = order
        self.quantity = quantity
        self.address = address

    def setName( self, newName ):
        self.Name = newName
    def setOrder ( self, newModel ):
        self.model = newModel
    def setQuantity ( self, newQuantity ):
        self.quantity = newQuantity
    def setAddress (self, newAddress ):
        self.address = newAddress

    def getName ( self ):
        return self.name
    def getOrder ( self ):
        return self.order
    def getQuantity ( self ):
        return self.quantity
    def getAddress ( self ):
        return self.address

name = input("Enter your name: ")
order = input("Enter your order: ")
quantity = int(input("Enter your quantity: "))
address = input("Enter your address: ")

customerObj = CustomerInfo()

print ( "Name: ", customerObj.name)
print ( "Order: ", customerObj.order)
print ( "Quanity: ", customerObj.quantity)
print ( "Address: ", customerObj.address)

I want to take input some information of customers like name, order, quantity and address but I get an exception TypeError: __init__() takes 0 positional arguments but 1 was given.

Enter your name: Python
Enter your order: 23
Enter your quantity: 21
Enter your address: 333 West USA
Traceback (most recent call last):
  File "main.py", line 32, in <module>
    customerObj = CustomerInfo()
TypeError: __init__() takes 0 positional arguments but 1 was given

How can I fix it? Anyone can explain to me.

Thanks for any suggestions.

Have 2 answer(s) found.

  • Leonardo Urbano
    Sep 05 2021

    Method __init__ () should be accepted self in Python because, well, it’s a method.

    Change:

    TO:

    And it solved the issue for you.

  • Watcharapong Jakkawannorasing
    Sep 05 2021

    Hey, I think this is the message throw when you forget (self,...) arg in __init__() or any other method.

    Add self param and it is solved for you.

Related Q&A May You Like

  1. TypeError: cannot unpack non-iterable NoneType object in Python
  2. AttributeError: ‘set’ object has no attribute ‘extend’ in Python
  3. ModuleNotFoundError: No module named ‘click’ in Python
  4. ImportError: cannot import name ‘get_config’ from ‘tensorflow.python.eager.context’
  5. Error: pg_config executable not found in Python 3.10
  6. ValueError: Can only compare identically-labeled DataFrame objects in Python
  7. ValueError: I/O operation on closed file in Python 3
  8. AttributeError: ‘dict’ object has no attribute ‘has_key’ in Python
  9. AttributeError: type object ‘datetime.datetime’ has no attribute ‘timedelta’ in Python
  10. AttributeError: ‘DataFrame’ object has no attribute ‘as_matrix’ in Python
  11. AttributeError: ‘DataFrame’ object has no attribute ‘price’ in Python
  12. SyntaxError: non-default argument follows default argument in Python
  13. Error: BrokenPipeError: [Errno 32] Broken pipe in Python 3
  14. Throw ImportError: No module named boto3 in Python 3
  15. AttributeError: ‘str’ object has no attribute ‘decode’ in Python

Leave An Answer

* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ятрогенная патология врачебные ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Smode panel controller smh 2010 сброс ошибок