Меню

Takes 1 positional argument but 2 were given python ошибка

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.

Get offers and scholarships from top coding schools illustration

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

Email

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!

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.

Avatar Of Srinivas Ramakrishna

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.

From teaching hundreds of thousands of students Python, I found this error to be a classic. I think understanding classes is hard enough, but many coders who’ve just started to learn about Python are rightly confused ? about the TypeError that complains about too few positional arguments. Let’s resolve this confusion once and for all, shall we?

Problem Formulation: Method Takes One Arguments But Two Are Given

Consider the following minimal example where this error occurs. Most occurrences of this error are variants of the following usage—you define method with one argument, but when calling it with one argument, Python raises the error:

class YourClass:
    def method(your_arg): # One positional argument defined
        print(your_arg)

o = YourClass()
o.method('finxter') # Calling it with one argument

However, this code snippet raises an error: TypeError: method() takes 1 positional argument but 2 were given

Traceback (most recent call last):
  File "C:UsersxcentDesktopcode.py", line 6, in <module>
    o.method('finxter')
TypeError: method() takes 1 positional argument but 2 were given

Here’s how it looks in my IDLE shell:

What is the origin of this error?

Solution: First Positional Argument Must be Self

You can solve the TypeError: method() takes 1 positional argument but 2 were given by adding an argument named self to your method definition as a first positional argument. But when calling it, you skip the name, so you’d define method(self, arg) but call method(arg). Python implicitly passes a reference to the instance as a first method argument, that’s why it tells you that two arguments are given.

class YourClass:
    def method(self, your_arg): # One positional argument defined
        print(your_arg)

o = YourClass()
o.method('finxter') # Calling it with one argument

Now, the output doesn’t contain an error:

finxter

The reason is simple: the first keyword is a reference to the instance on which it is called. So, if you call

o.method('finxter')

Python automatically converts it to

YourClass.method(o, 'finxter')

passing the instance on which it is called as a first positional argument usually named self. This is just syntactic sugar but you need to understand it once to overcome your confusion forever.

Background

The name self is, by convention, the name of the first argument of a Python class method. The variable self points to the concrete instance on which the method is called. It is used within the method to access attributes and other methods of the same instance. The caller of the method does not explicitly pass the instance into self but leaves it to the Python interpreter to pass it automatically. For example, given an object car, Python automatically converts the method call car.drive() to drive(self=car).

Python Self in Object-Oriented Programming [Simple Guide]

Feel free to join our community of ambitious coders and download your cheat sheets:

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

Brief blog post on a silly Python error. I’m still working on my ML project started hypertuning my sklearn pipeline — manually. To set the parameters of my pipeline in every iteration, I had to use set_params.

My estimator is called model_pipeline and I needed to set the parameters via a dictionary for a particular situation, via the set_params method.

model_pipeline.set_params(params)

I expected it to work. But when I ran that line of code, this is the error that I ran into:

set_params() takes 1 positional argument but 2 were given

It’s a common Python error, not specifically tied to a Pipeline or even scikit-learn, that I’ll spend some time on in this blog post.


If you consult the set_params documentation, you will read the following:

set_params(**kwargs)      Set the parameters of this estimator.

See those two asterisks? You probably have already encountered it in a Python function’s documentation; they’re actually pretty important if you want to use Python efficiently.

  • *args: accepts any number of positional arguments via a tuple
  • **kwargs: accepts any number of keyword arguments via a dictionary

The arguments args and kwargs are variables and will contain, respectively, the tuple or dictionary that you pass it. You can even name them whatever you want — but only if you want to piss off someone from your team. The following code will simply print the dictionary I passed to the badger function.

def badger(**fruit):
    return fruit

badger(**{'apples': 4, 'pears': 3})

And if you want to piss off not only your colleague, but your whole team, try mixing both of them with regular arguments in a random position — really, don’t.

def badger(mice, ants = None, *fruit, eggs = None, **vegetables): 
    return mouse, ant, fruit, egg, plants
  
badger(6, 7, ants = *(8, 9, 10, 11, 12), 13, 14, fruit = **{'broccoli': 15, 'cabbage': 16})

There we go. From a very specific situation to a very general blog post. Hope you learned something.

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

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

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

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

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Take on mars ошибка при запуске unhandled exception
  • Tag start is not closed ошибка