TypeError: takes 0 positional arguments but 1 was given
TypeError: takes 0 positional arguments but 1 was given in Python means called on an object, a method always receives the object itself as its first argument. A method defined without self cannot accept it.
How do I fix TypeError: takes 0 positional arguments but 1 was given?
TypeError: takes 0 positional arguments but 1 was given usually means a method inside a class is missing self. Calling obj.method() passes obj as the first argument, so def method(): cannot accept it. Change it to def method(self):, or add @staticmethod if the method never uses the object.
- 1. Is it a method?If the call is obj.name(), the def inside the class must start with self as its first parameter.
- 2. Count both sidesPut the def line and the call side by side. Add one argument for the object on obj.name() calls.
- 3. Plain function callsFor a normal function, add the missing parameter to def, or remove the extra argument from the call.
What does TypeError: takes 0 positional arguments but 1 was given mean?
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.
Why does TypeError: takes 0 positional arguments but 1 was given happen?
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.
Try it: fix this bug
mediumcount_clicks(3) crashes: TypeError: Counter.increment() takes 0 positional arguments but 1 was given.
class Counter:
def __init__(self):
self.count = 0
def increment():
self.count += 1
def count_clicks(n):
counter = Counter()
for _ in range(n):
counter.increment()
return counter.countStill 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.