TypeError: takes 0 positional arguments but 1 was given
Called on an object, a method always receives the object itself as its first argument. A method defined without self cannot accept it.
What it means
obj.method() is shorthand for Class.method(obj), so Python passes one argument even though your brackets are empty. If the definition is def method():, it accepts none, and the counts disagree. Ordinary functions called with too many arguments raise the same message.
Common causes
1. A method without self
Every instance method needs self as its first parameter.
Breaks
class Counter:
def increment():
self.count += 1Works
class Counter:
def increment(self):
self.count += 12. Calling a function with an argument it does not take
The definition and the call disagree about what the function needs.
Breaks
def greet():
return "Hello"
greet("Asha")Works
def greet(name):
return "Hello, " + name
greet("Asha")3. A method that should be static
If it never uses the object, mark it so Python stops passing one.
Breaks
class MathUtils:
def square(x):
return x * xWorks
class MathUtils:
@staticmethod
def square(x):
return x * xHow to find it in your own code
Put the def line and the call side by side and count arguments, adding one for the object when the call is obj.name(...). If you are one short, the def is missing self.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.