When you call a method associated with an object, there is one positional argument that is supplied by default: self. If you forget to include “self” when you define a method, you’ll encounter an error that says “takes 1 positional argument but 2 were given”.
In this article, we discuss this error and why it is raised. We walk through an example of this error to help you figure out how to solve it in your code.
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
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.
takes 1 positional argument but 2 were given
Python passes an argument called “self” into every method in an object. “self” is similar to “this” in JavaScript. The “self” argument stores information about the values in an object.
“self” is passed into methods by default because most methods rely on the values that have been assigned to an object in some way.
All methods defined in a class must have an argument called “self”. If you specify an argument other than “self” without including “self”, Python will return the “takes 1 positional argument but 2 were given” error.
This is because Python passes “self” into a method by default and so it expects there is room for “self” in addition to any other arguments that a method should receive.
An Example Scenario
Write a class that stores information on television show characters. Start by declaring our class and defining a constructor that stores the values we pass into our class:
class Character: def __init__(self, character_name, real_name, show): self.character_name = character_name self.real_name = real_name self.show = show
Write a function that lets us change the value of “show”:
def change_show(show): self.show = show print(show)
This method changes the value of “show” in our class and prints out the value of “show” to the console. To test out this method, we have to define an instance of our object and call the change_show()
method:
sam_malone = Character("Sam Malone", "Ted Danson", "") sam_malone.change_show("Cheers")
Our “sam_malone” object is initialized with the following values:
- Character Name: Sam Malone
- Real Name: Ted Danson
- Show: [Empty]
We have left the value of “show” empty because we’re going to add it in later. Next, we use the change_show()
method to set the value of “show” to “Cheers”.
Run our code:
Traceback (most recent call last): File "main.py", line 11, in <module> sam_malone.change_show("Cheers") TypeError: change_show() takes 1 positional argument but 2 were given
Our code does not execute successfully.
The Solution
In our code, we have not passed “self” into our change_show()
method.
Python passes “self” as a parameter every time you call a method of an object. In our above code, Python is executing:
sam_malone.change_show("Cheers")
Another way of representing this is:
Character.change_show(sam_malone, "Cheers")
This shows that our object, “sam_malone”, is actually passed into our method. To solve this error, we have to specify “self” as an argument in our class:
def change_show(self, show): self.show = show print(show)
This tells the change_show()
method to expect two arguments: “self” and “show”. “self” is the object on which the method will be executed. “show” is the name of the television show with which a character is associated.
Run our code again with our new function:
Our code prints the value of “show” to the console successfully. Every time we reference “show” in our class after we have called change_show()
, the value associated with “show” is “Cheers”.
Conclusion
The “takes 1 positional argument but 2 were given” error is raised when you try to pass an argument through a method in a class without also specifying “self” as an argument.
You solve this error by adding “self” as an argument to all the methods in a class.
Now you’re ready to solve this error in your code like a professional coder!
Typeerror: takes 1 positional argument but 2 were given is the error you get when you create a Class and call the specific method by creating an object of the class. It happens as you forget to include self parameters in the methods of the class. In this entire tutorial, you will understand how you can overcome this typeerror quickly using various ways.
Why this error comes? Let’s understand it by creating a Sample Class and calling a Class method by creating an object of the it.
Execute the below lines of code to create a class.
class SampleClass:
def fun(arg):
print(arg)
Now let’s create an object of the class and call the “fun ” function name.
obj = SampleClass()
obj.fun("Data Science Learner")
When you will run the code you will get the fun() takes 1 positional argument but 2 were given error.
It is giving this error as you have not passed the default self parameter for the method func(). You should note that every method that is present inside the class must have a self argument. It is done to tell the interpreter that this method is the method of the class.
How to Solve this issue
To solve this ” Typeerror: takes 1 positional argument but 2 were given ” is by adding self argument for each method inside the class. It will remove the error.
Taking the same example if I will execute the below lines of code then I will not get the error.
class SampleClass:
def fun(self,arg):
print(arg)
obj = SampleClass()
obj.fun("Data Science Learner")
Output
Other Solution
The other way to solve this typeerror is making the method of the class to static method. This way you don’t have to add the self-argument for the method.
You have to just decorate the method with the @staticmethod above the function name.
Execute the below lines of code.
class SampleClass:
@staticmethod
def fun(arg):
print(arg)
obj = SampleClass()
obj.fun("Data Science Learner")
Output
Conclusion
Typeerror: takes 1 positional argument but 2 were given error comes mostly when you forget to add “self” argument for the method inside the class. These are the way to solve this type of Typeerror.
I hope this tutorial has solved your queries. Even if you have doubts then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
We respect your privacy and take protecting it seriously
Thank you for signup. A Confirmation Email has been sent to your Email Address.
Something went wrong.
If you define a method inside a class, you should add self
as the first argument. If you forget the self argument, then Python will raise TypeError: method() takes 1 positional argument but 2 were given
In this tutorial, we will look at what method() takes 1 positional argument but 2 were given error means and how to resolve this error with examples.
In Python, we need to pass “self
” as the first argument for all the methods which is defined in a class. It is similar to this in JavaScript.
We know that class is a blueprint for the objects, and we can use the blueprints to create multiple instances of objects.
The self
is used to represent the instance(object) of the class. Using this keyword, we can access the attributes and methods of the class in Python.
Let us take a simple example to reproduce this error.
If you look at the below example, we have an Employee class, and we have a simple method that takes the name as a parameter and prints the Employee ID as output.
# Employee Class
class Employee:
# Get Employee method without self parameter
def GetEmployeeID(name):
print(f"The Employee ID of {name} ", 1234)
# instance of the employee
empObj = Employee()
empObj.GetEmployeeID("Chandler Bing")
Output
Traceback (most recent call last):
File "c:PersonalIJSCodemain.py", line 10, in <module>
empObj.GetEmployeeID("Chandler Bing")
TypeError: Employee.GetEmployeeID() takes 1 positional argument but 2 were given
When we run the code, we get a TypeError: method() takes 1 positional argument but 2 were given
How to fix TypeError: method() takes 1 positional argument but 2 were given
In our above code, we have not passed the self argument to the method defined in the Employee class, which leads to TypeError.
As shown below, we can fix the issue by passing the “self
” as a parameter explicitly to the GetEmployeeID()
method.
# Employee Class
class Employee:
# Get Employee method with self parameter
def GetEmployeeID(self,name):
print(f"The Employee ID of {name} ", 1234)
# instance of the employee
empObj = Employee()
empObj.GetEmployeeID("Chandler Bing")
Output
The Employee ID of Chandler Bing 1234
In Python, when we call the method with some arguments, the corresponding class function is called by placing the methods object before the first argument.
Example – object.method(args)
will become Class.method(obj,args)
.
The calling process is automatic, but it should be defined explicitly on the receiving side.
This is one of the main reasons the first parameter of a function in a class must be the object itself.
It is not mandatory to use “self
” as an argument; instead, we can pass anything over here.
The “self
” is neither a built-in keyword nor has special meaning in Python. It is just a better naming convention that developers use and improves the readability of the code.
Conclusion
The TypeError: method() takes 1 positional argument but 2 were given occurs if we do not pass the “self” as an argument to all the methods defined inside the class.
The self is used to represent the instance(object) of the class. Using this keyword, we can access the attributes and methods of the class in Python.
The issue is resolved by passing the “self
” as a parameter to all the methods defined in a class.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
Получаю данную ошибку: TypeError: generator() takes 1 positional argument but 2 were given
Я хочу чтобы при нажатии на кнопку в консоль писался hello world, но что-то идёт не так. Заранее спасибо!
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.config import Config
Config.set('graphics', 'resizable', 0)
Config.set('graphics', 'height', 500)
Config.set('graphics', 'width', 500)
class PasswordGeneratorApp(App):
def generator(self):
print('Hello world!')
def build(self):
appbuild = GridLayout()
appbuild.add_widget( Button(text = "сгенерировать", background_normal = "", background_color = [.96, .77, .15, 1], on_press = self.generator))
return appbuild
if __name__ == "__main__":
PasswordGeneratorApp().run()
Ошибка:
Traceback (most recent call last):
File "pass.py", line 26, in <module>
PasswordGeneratorApp().run()
File "C:Python365libsite-packageskivyapp.py", line 828, in run
runTouchApp()
File "C:Python365libsite-packageskivybase.py", line 504, in runTouchApp
EventLoop.window.mainloop()
File "C:Python365libsite-packageskivycorewindowwindow_sdl2.py", line 663, in mainloop
self._mainloop()
File "C:Python365libsite-packageskivycorewindowwindow_sdl2.py", line 405, in _mainloop
EventLoop.idle()
File "C:Python365libsite-packageskivybase.py", line 342, in idle
self.dispatch_input()
File "C:Python365libsite-packageskivybase.py", line 327, in dispatch_input
post_dispatch_input(*pop(0))
File "C:Python365libsite-packageskivybase.py", line 233, in post_dispatch_input
listener.dispatch('on_motion', etype, me)
File "kivy_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy_event.c:8191)
File "C:Python365libsite-packageskivycorewindow__init__.py", line 1188, in on_motion
self.dispatch('on_touch_down', me)
File "kivy_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy_event.c:8191)
File "C:Python365libsite-packageskivycorewindow__init__.py", line 1204, in on_touch_down
if w.dispatch('on_touch_down', touch):
File "kivy_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy_event.c:8191)
File "C:Python365libsite-packageskivyuixwidget.py", line 457, in on_touch_down
if child.dispatch('on_touch_down', touch):
File "kivy_event.pyx", line 718, in kivy._event.EventDispatcher.dispatch (kivy_event.c:8191)
File "C:Python365libsite-packageskivyuixbehaviorsbutton.py", line 151, in on_touch_down
self.dispatch('on_press')
File "kivy_event.pyx", line 714, in kivy._event.EventDispatcher.dispatch (kivy_event.c:8146)
File "kivy_event.pyx", line 1225, in kivy._event.EventObservers.dispatch (kivy_event.c:14035)
File "kivy_event.pyx", line 1149, in kivy._event.EventObservers._dispatch (kivy_event.c:13564)
TypeError: generator() takes 1 positional argument but 2 were given
Problem:
You are trying to run your Python unit tests using the unittest package, but you see this unspecific stack trace:
Traceback (most recent call last): File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/lib/python3.7/unittest/__main__.py", line 18, in <module> main(module=None) File "/usr/lib/python3.7/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/usr/lib/python3.7/unittest/main.py", line 124, in parseArgs self._do_discovery(argv[2:]) File "/usr/lib/python3.7/unittest/main.py", line 244, in _do_discovery self.createTests(from_discovery=True, Loader=Loader) File "/usr/lib/python3.7/unittest/main.py", line 154, in createTests self.test = loader.discover(self.start, self.pattern, self.top) File "/usr/lib/python3.7/unittest/loader.py", line 349, in discover tests = list(self._find_tests(start_dir, pattern)) File "/usr/lib/python3.7/unittest/loader.py", line 414, in _find_tests yield from self._find_tests(full_path, pattern, namespace) File "/usr/lib/python3.7/unittest/loader.py", line 406, in _find_tests full_path, pattern, namespace) File "/usr/lib/python3.7/unittest/loader.py", line 460, in _find_test_path return self.loadTestsFromModule(module, pattern=pattern), False File "/usr/lib/python3.7/unittest/loader.py", line 124, in loadTestsFromModule tests.append(self.loadTestsFromTestCase(obj)) File "/usr/lib/python3.7/unittest/loader.py", line 93, in loadTestsFromTestCase loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames)) File "/usr/lib/python3.7/unittest/suite.py", line 24, in __init__ self.addTests(tests) File "/usr/lib/python3.7/unittest/suite.py", line 57, in addTests for test in tests: TypeError: __init__() takes 1 positional argument but 2 were given
Solution:
You have at least one test case like this one:
class MyTest(unittest.TestCase): def __init__(self): self.x = 1.0 def test_stuff(self): assert(self.x == 1.0)
Overriding __init__(...)
is not possible in this way when using unittest. You need to use setUp()
instead.
Usually, just replacing def __init__(self):
by def setUp(self):
will do the trick. unittests will call setUp()
automatically.
Our example will look like this:
class MyTest(unittest.TestCase): def setUp(self): self.x = 1.0 def test_stuff(self): assert(self.x == 1.0)
If the error still persists, check if you have more testcases overriding the __init__()
method.