Ошибка takes 1 positional argument but 2 were given

If I have a class …

class MyClass:

    def method(arg):
        print(arg)

… which I use to create an object …

my_object = MyClass()

… on which I call method("foo") like so …

>>> my_object.method("foo")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 1 positional argument (2 given)

… why does Python tell me I gave it two arguments, when I only gave one?

wjandrea's user avatar

wjandrea

27.2k9 gold badges59 silver badges80 bronze badges

asked May 29, 2014 at 23:27

Zero Piraeus's user avatar

Zero PiraeusZero Piraeus

55.6k27 gold badges150 silver badges159 bronze badges

1

In Python, this:

my_object.method("foo")

… is syntactic sugar, which the interpreter translates behind the scenes into:

MyClass.method(my_object, "foo")

… which, as you can see, does indeed have two arguments — it’s just that the first one is implicit, from the point of view of the caller.

This is because most methods do some work with the object they’re called on, so there needs to be some way for that object to be referred to inside the method. By convention, this first argument is called self inside the method definition:

class MyNewClass:

    def method(self, arg):
        print(self)
        print(arg)

If you call method("foo") on an instance of MyNewClass, it works as expected:

>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo

Occasionally (but not often), you really don’t care about the object that your method is bound to, and in that circumstance, you can decorate the method with the builtin staticmethod() function to say so:

class MyOtherClass:

    @staticmethod
    def method(arg):
        print(arg)

… in which case you don’t need to add a self argument to the method definition, and it still works:

>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo

answered May 29, 2014 at 23:27

Zero Piraeus's user avatar

Zero PiraeusZero Piraeus

55.6k27 gold badges150 silver badges159 bronze badges

2

In simple words

In Python you should add self as the first parameter to all defined methods in classes:

class MyClass:
  def method(self, arg):
    print(arg)

Then you can use your method according to your intuition:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

For a better understanding, you can also read the answers to this question: What is the purpose of self?

wjandrea's user avatar

wjandrea

27.2k9 gold badges59 silver badges80 bronze badges

answered Jun 19, 2019 at 9:44

simhumileco's user avatar

simhumilecosimhumileco

31.3k16 gold badges137 silver badges112 bronze badges

3

Something else to consider when this type of error is encountered:

I was running into this error message and found this post helpful. Turns out in my case I had overridden an __init__() where there was object inheritance.

The inherited example is rather long, so I’ll skip to a more simple example that doesn’t use inheritance:

class MyBadInitClass:
    def ___init__(self, name):
        self.name = name

    def name_foo(self, arg):
        print(self)
        print(arg)
        print("My name is", self.name)


class MyNewClass:
    def new_foo(self, arg):
        print(self)
        print(arg)


my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")

Result is:

<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
  File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
    my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters

PyCharm didn’t catch this typo. Nor did Notepad++ (other editors/IDE’s might).

Granted, this is a «takes no parameters» TypeError, it isn’t much different than «got two» when expecting one, in terms of object initialization in Python.

Addressing the topic: An overloading initializer will be used if syntactically correct, but if not it will be ignored and the built-in used instead. The object won’t expect/handle this and the error is thrown.

In the case of the sytax error: The fix is simple, just edit the custom init statement:

def __init__(self, name):
    self.name = name

simhumileco's user avatar

simhumileco

31.3k16 gold badges137 silver badges112 bronze badges

answered Jan 4, 2016 at 4:33

Jonru's user avatar

3

This issue can also be caused by failing to pass keyword arguments to a function properly.

For example, given a method defined like:

def create_properties_frame(self, parent, **kwargs):

a call like this:

self.create_properties_frame(frame, kw_gsp)

will cause TypeError: create_properties_frame() takes 2 positional arguments but 3 were given, because the kw_gsp dictionary is treated as a positional argument instead of being unpacked into separate keyword arguments.

The solution is to add ** to the argument:

self.create_properties_frame(frame, **kw_gsp)

Karl Knechtel's user avatar

Karl Knechtel

61.7k11 gold badges98 silver badges148 bronze badges

answered Jul 28, 2019 at 9:43

Stanislav Pankevich's user avatar

2

As mentioned in other answers — when you use an instance method you need to pass self as the first argument — this is the source of the error.

With addition to that,it is important to understand that only instance methods take self as the first argument in order to refer to the instance.

In case the method is Static you don’t pass self, but a cls argument instead (or class_).

Please see an example below.

class City:

   country = "USA" # This is a class level attribute which will be shared across all instances  (and not created PER instance)

   def __init__(self, name, location, population):
       self.name       = name
       self.location   = location
       self.population = population
 
   # This is an instance method which takes self as the first argument to refer to the instance 
   def print_population(self, some_nice_sentence_prefix):
       print(some_nice_sentence_prefix +" In " +self.name + " lives " +self.population + " people!")

   # This is a static (class) method which is marked with the @classmethod attribute
   # All class methods must take a class argument as first param. The convention is to name is "cls" but class_ is also ok
   @classmethod
   def change_country(cls, new_country):
       cls.country = new_country

Some tests just to make things more clear:

# Populate objects
city1 = City("New York",    "East", "18,804,000")
city2 = City("Los Angeles", "West", "10,118,800")

#1) Use the instance method: No need to pass "self" - it is passed as the city1 instance
city1.print_population("Did You Know?") # Prints: Did You Know? In New York lives 18,804,000 people!

#2.A) Use the static method in the object
city2.change_country("Canada")

#2.B) Will be reflected in all objects
print("city1.country=",city1.country) # Prints Canada
print("city2.country=",city2.country) # Prints Canada

answered Jul 1, 2020 at 19:45

RtmY's user avatar

RtmYRtmY

17.2k12 gold badges113 silver badges119 bronze badges

3

It occurs when you don’t specify the no of parameters the __init__() or any other method looking for.

For example:

class Dog:
    def __init__(self):
        print("IN INIT METHOD")

    def __unicode__(self,):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")

obj = Dog("JIMMY", 1, 2, 3, "WOOF")

When you run the above programme, it gives you an error like that:

TypeError: __init__() takes 1 positional argument but 6 were given

How we can get rid of this thing?

Just pass the parameters, what __init__() method looking for

class Dog:
    def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
        self.name_of_dog = dogname
        self.date_of_birth = dob_d
        self.month_of_birth = dob_m
        self.year_of_birth = dob_y
        self.sound_it_make = dogSpeakText

    def __unicode__(self, ):
        print("IN UNICODE METHOD")

    def __str__(self):
        print("IN STR METHOD")


obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))

wjandrea's user avatar

wjandrea

27.2k9 gold badges59 silver badges80 bronze badges

answered Feb 3, 2017 at 3:45

Trinadh Koya's user avatar

Trinadh KoyaTrinadh Koya

1,08915 silver badges19 bronze badges

0

If you want to call method without creating object, you can change method to static method.

class MyClass:

    @staticmethod
    def method(arg):
        print(arg)

MyClass.method("i am a static method")

answered Aug 12, 2021 at 14:40

Manikandan Raju's user avatar

I get this error when I’m sleep-deprived, and create a class using def instead of class:

def MyClass():
    def __init__(self, x):
        self.x = x

a = MyClass(3)
-> TypeError: MyClass() takes 0 positional arguments but 1 was given

wjandrea's user avatar

wjandrea

27.2k9 gold badges59 silver badges80 bronze badges

answered Mar 9, 2021 at 14:43

Simon Alford's user avatar

Simon AlfordSimon Alford

2,3451 gold badge12 silver badges10 bronze badges

3

If you experience this with Django then this is what it implies:

  1. add an object to the function, Django will understand the rest, example
def display_genre(self, obj):
        return ', '.join(genre.name for genre in obj.genre.all())}

answered Mar 30 at 11:29

King Chudi's user avatar

In my case, I forgot to add the ()

I was calling the method like this

obj = className.myMethod

But it should be is like this

obj = className.myMethod()

answered Jun 5, 2020 at 19:36

Gabriel Arghire's user avatar

Gabriel ArghireGabriel Arghire

1,8931 gold badge19 silver badges34 bronze badges

2

You should actually create a class:

class accum:
    def __init__(self):
        self.acc = 0
    def accumulator(self, var2add, end):
        if not end:
            self.acc+=var2add
        return self.acc

answered Jan 17, 2020 at 17:16

Coddy's user avatar

CoddyCoddy

5484 silver badges18 bronze badges

1

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.

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

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.

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!

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.

takes 1 positional argument but 2 were given Error

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

Solved takes 1 positional argument but 2 were given Error

Solved takes 1 positional argument but 2 were given Error

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

Solved takes 1 positional argument but 2 were given Error using static method

Solved takes 1 positional argument but 2 were given Error using the static method

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. Please visit this generic informative article on typeerror in Python to strengthen the depth of the topic.

typeerror: exceptions must derive from baseexception – Fix Quickly

Thanks

Data Science Learner Team

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.

Learn Algorithms and become a National Programmer

Indian Technical Authorship Contest starts on 1st July 2023. Stay tuned.

In this article, we have explained the reason behind the Python error «<lambda>() takes 1 positional argument but 2 were given» and have presented multiple ways in which this error can be fixed.

Table of contents:

  1. Understanding the error
  2. Fix 1: Basic case
  3. Fix 2: Error with reduce()
  4. Concluding Note

Understanding the error

While running a Python code which uses lambda you may encounter the following error:

Traceback (most recent call last):
  File "opengenus.py", line 4, in <module>
    a = reduce(f, list)
TypeError: <lambda>() takes 1 positional argument but 2 were given

The problem is that the lambda defined in the code takes 1 input parameter but during the invocation of the lambda function 2 input parameters are passed and hence, the error.

The fix will involve:

  • Updating the lambda to take 2 inputs
  • OR, update the way lambda is called so correct number of input arguments are passed.

There could be other variants of this error when there is a mismatch between the number of parameters expected by the lambda and the number of parameters passed to the lambda. For example:

TypeError: <lambda>() takes 1 positional argument but 2 were given
TypeError: <lambda>() takes 1 positional argument but 2 were given

We will explore how to fix this error.

Fix 1: Basic case

Consider the following Python code which defined a lambda that takes 1 input and adds one to it but while calling the lambda, we are passing two input values. This is the case where the error will come.

f = lambda x: x+1
a = f(4, 3)
print(a)

Run it as:

python code.py

Error:

Traceback (most recent call last):
  File "opengenus.py", line 4, in <module>
    a = reduce(f, list)
TypeError: <lambda>() takes 1 positional argument but 2 were given

The fix is simple. Call the lambda with one element at a time as the lambda is designed to take 1 input parameter. In some code, lambda can take 2 or more input parameters as well.

The fixed Python code is as follows:

f = lambda x: x+1
a = f(4)
print(a)

Output:

5

Similarly, make sure that the lambda is not called with less number of input parameters than expected by the lambda.

Fix 2: Error with reduce()

One case when the error may come is during the use of reduce(). Reduce() built-in function is frequently used to call a lambda function on repeatedly on each element of an iterable.

Consider the following code:

from functools import reduce
list = [91, 12, 63, 5] 
f = lambda x: print(x)
a = reduce(f, list)

Run it as:

python code.py

Error:

Traceback (most recent call last):
  File "opengenus.py", line 4, in <module>
    a = reduce(f, list)
TypeError: <lambda>() takes 1 positional argument but 2 were given

This issue is reduce() invokes the lambda with two parameters and hence, a fix will be to update the lambda to take 2 input parameters. Consider the following Python code which fixes the issue:

from functools import reduce
list = [91, 12, 63, 5] 
f = lambda x, y: print(x, y)
a = reduce(f, list)

Output:

91 12
None 63
None 5

Concluding Note

With this article at OpenGenus, you must have the complete idea of how to fix this error of <lambda>() takes 1 positional argument but 2 were given.

Always check if the definition of a function and if you are calling the function as expected.

Понравилась статья? Поделить с друзьями:
  • Ошибка system32 drivers ntfs sys
  • Ошибка takes 0 positional arguments but 1 was given
  • Ошибка system will shut down
  • Ошибка table was not locked with lock tables
  • Ошибка system volume information что это