Меню

Missing 1 required positional argument self ошибка

I can’t get past the error:

Traceback (most recent call last):
  File "C:UsersDomDesktoptesttest.py", line 7, in <module>
    p = Pump.getPumps()
TypeError: getPumps() missing 1 required positional argument: 'self'

I examined several tutorials but there doesn’t seem to be anything different from my code. The only thing I can think of is that Python 3.3 requires different syntax.

class Pump:

    def __init__(self):
        print("init") # never prints

    def getPumps(self):
        # Open database connection
        # some stuff here that never gets executed because of error
        pass  # dummy code

p = Pump.getPumps()

print(p)

If I understand correctly, self is passed to the constructor and methods automatically. What am I doing wrong here?

Kai - Kazuya Ito's user avatar

asked Jul 8, 2013 at 19:21

DominicM's user avatar

You need to instantiate a class instance here.

Use

p = Pump()
p.getPumps()

Small example —

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

gl393's user avatar

gl393

3013 silver badges14 bronze badges

answered Jul 8, 2013 at 19:23

Sukrit Kalra's user avatar

Sukrit KalraSukrit Kalra

32.2k7 gold badges66 silver badges70 bronze badges

0

You need to initialize it first:

p = Pump().getPumps()

answered Jul 8, 2013 at 19:23

JBernardo's user avatar

JBernardoJBernardo

31.6k10 gold badges89 silver badges114 bronze badges

0

Works and is simpler than every other solution I see here :

Pump().getPumps()

This is great if you don’t need to reuse a class instance. Tested on Python 3.7.3.

answered May 18, 2019 at 9:50

Jay D.'s user avatar

Jay D.Jay D.

1,2323 gold badges15 silver badges26 bronze badges

1

The self keyword in Python is analogous to this keyword in C++ / Java / C#.

In Python 2 it is done implicitly by the compiler (yes Python does compilation internally).
It’s just that in Python 3 you need to mention it explicitly in the constructor and member functions. example:

class Pump():
    # member variable
    # account_holder
    # balance_amount

    # constructor
    def __init__(self,ah,bal):
        self.account_holder = ah
        self.balance_amount = bal

    def getPumps(self):
        print("The details of your account are:"+self.account_number + self.balance_amount)

# object = class(*passing values to constructor*)
p = Pump("Tahir",12000)
p.getPumps()

Ghost Ops's user avatar

Ghost Ops

1,6902 gold badges12 silver badges23 bronze badges

answered Feb 19, 2019 at 13:21

Tahir77667's user avatar

Tahir77667Tahir77667

2,11816 silver badges15 bronze badges

4

You can call the method like pump.getPumps(). By adding @classmethod decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.

class Pump:

def __init__(self):
    print ("init") # never prints

@classmethod
def getPumps(cls):
            # Open database connection
            # some stuff here that never gets executed because of error

So, simply call Pump.getPumps() .

In java, it is termed as static method.

answered Sep 4, 2020 at 9:23

Atom's user avatar

AtomAtom

2306 silver badges13 bronze badges

1

You can also get this error by prematurely taking PyCharm’s advice to annotate a method @staticmethod. Remove the annotation.

answered Dec 3, 2017 at 15:58

gherson's user avatar

ghersongherson

1392 silver badges9 bronze badges

I got the same error below:

TypeError: test() missing 1 required positional argument: ‘self’

When an instance method had self, then I called it directly by class name as shown below:

class Person:
    def test(self): # <- With "self" 
        print("Test")

Person.test() # Here

And, when a static method had self, then I called it by object or directly by class name as shown below:

class Person:
    @staticmethod
    def test(self): # <- With "self" 
        print("Test")

obj = Person()
obj.test() # Here

# Or

Person.test() # Here

So, I called the instance method with object as shown below:

class Person:
    def test(self): # <- With "self" 
        print("Test")

obj = Person()
obj.test() # Here

And, I removed self from the static method as shown below:

class Person:
    @staticmethod
    def test(): # <- "self" removed 
        print("Test")

obj = Person()
obj.test() # Here

# Or

Person.test() # Here

Then, the error was solved:

Test

In detail, I explain about instance method in my answer for What is an «instance method» in Python? and also explain about @staticmethod and @classmethod in my answer for @classmethod vs @staticmethod in Python.

answered Nov 15, 2022 at 15:19

Kai - Kazuya Ito's user avatar

Kai — Kazuya ItoKai — Kazuya Ito

14.5k9 gold badges86 silver badges98 bronze badges

If skipping parentheses for the object declaration (typo), then exactly this error occurs.

# WRONG! will result in TypeError: getPumps() missing 1 required positional argument: 'self'
p = Pump
p.getPumps()

Do not forget the parentheses for the Pump object

# CORRECT!
p = Pump()
p.getPumps()

answered Nov 21, 2022 at 9:52

Daniel Nelson's user avatar

Daniel NelsonDaniel Nelson

1,6781 gold badge11 silver badges11 bronze badges

The Python error “TypeError: missing 1 required positional argument: ‘self’” happens when you call a class method on the class itself instead of an object of that class. You can fix this by instantiating the class first.

If you have created your own class, then try to call a method of it, what do you think will happen? Take the below class for example:

class Foo:
    def say_hello(self):
        print("Hello there")
Foo.say_hello()

The class Foo has one method, say_hello. That method takes an argument called self, which in Python, is the same as this in other languages. Although, in most other languages, the this object is implied – you don’t have to declare it as an argument to the class’ methods. Python just had to be different, I suppose.

Anyway, if you look below the class declaration above, you’ll see that we try to call the say_hello method on the Foo class itself, sort of like calling a static method (or class method). When we try to do this, we get the following output:

Traceback (most recent call last):
  File "/home/user/main.py", line 5, in <module>
    Foo.say_hello()
TypeError: say_hello() missing 1 required positional argument: 'self'

There’s a couple things going on here. First of all, you’re calling a method of the Foo class on the class itself – this means there’s no self. I.e., it’s not an object. It’s just the method that’s attached to the class. So the required positional argument self, which is passed automatically by Python when you call an object’s method, is missing. Second of all, if what you really want is a static method, you should declare the method as such using special syntax which we’ll get into later.

Fix 1: Instantiate the class first

The first and most simple way to fix this is to instantiate the class. What this means, if you’re not familiar with the term, is to create an object of that class. Our Foo class doesn’t have a constructor, but that’s okay, Python will give it a default one – one that doesn’t do anything.

Below is an example that will work:

class Foo:
    def say_hello(self):
        print("Hello there")
foo = Foo()
foo.say_hello()
# -> Hello there

Much better. In the above example, we took the Foo class and instantiated it. That means we ran the constructor of the class (Foo()) and it returned an object, or an “instantiation”, of itself, which we stored in the foo variable.

Then, when we call foo.say_hello(), the Python interpreter passes a reference to the foo object into the function invisibly and automatically, which constitutes the self argument for say_hello.

Fix 2: Make the function a static method of the class

If you were actually trying to make a static method, or a “class method” as it’s sometimes called, there’s a way to do that too. Class methods are useful for lots of things, such as factory methods, singletons, or just doing things that logically fall under the purview of the class but aren’t necessarily tied to an instance of that class.

In Python, or more specifically, Python 3, we can make a static method with the following syntax:

class Foo:
    def say_hello(self):
        print("Hello there")
    @staticmethod
    def say_goodbye():
        print("Goodbye everyone")
foo = Foo()
foo.say_hello()
# -> Hello there
Foo.say_goodbye()
# -> Goodbye everyone

As you can see in the highlighted lines above, Python has an annotation for static methods to declare them as such. Note that there is no “self” argument for a static method. That’s because they are just a method that falls under the class’ namespace, and doesn’t need access to access any state that might be attached to an instance of that object.

Conclusion

In this post, we covered what causes “TypeError: missing 1 required positional argument: ‘self’” as well as a couple different ways to deal with it. One way you can fix this is to instantiate the class first, and call the method on the object. This will populate the “self” argument and prevent the error. The other way this error can be handled is to make the method a static method of the class. This makes it so that the self variable isn’t necessary.

Happy coding!

Python classes need to be instantiated, or called, before you can access their methods. If you forget to instantiate an object of a class and try to access a class method, you encounter an error saying “missing 1 required positional argument: ‘self’”.

In this guide, we talk about what this error means and why it is raised. We walk through an example of this error in action to help you learn how to fix it.

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.

missing 1 required positional argument: ‘self’

Positional arguments refer to data that is passed into a function. In a class, every function must be given the value “self”. The value of “self” is similar to “this” in JavaScript. “self” represents the data stored in an object of a class.

When you call a class method without first instantiating an object of that class, you get an error. This is because “self” has no value until an object has been instantiated.

The most common mistakes that are made that cause the “missing 1 required positional argument: ‘self’” error are:

  • Forgetting to instantiate an object of a class
  • Using the incorrect syntax to instantiate a class

Let’s walk through each of these causes individually.

Cause #1: Forgetting to Instantiate an Object

An object must be instantiated before you can access a method in a class.

Define a class that stores information about a hero in a video game:

class Hero:
	def __init__(self, name, player_type):
		self.name = name
		self.player_type = player_type

Next, we add a function to our class. Functions inside of classes are called methods. This method prints out the name of a player and their player type:

def show_player(self):
		print("Player Name: " + self.name)
		print("Player Type: " + self.player_type)

Try to access our class so that we can create a player: 

luke = Hero.show_player()

We have created an object that is assigned to the variable “luke”. This object is derived from the Hero class. We call the show_player() method to show information about the player.

Let’s run our code altogether and see what happens:

Traceback (most recent call last):
  File "main.py", line 10, in <module>
	luke = Hero.show_player()
TypeError: show_player() missing 1 required positional argument: 'self'

Our code fails. This is because we have not instantiated an object of Hero. Hero.show_player() does not work because we haven’t created a Hero whose information can be displayed.

To solve this error, we first instantiate an object before we call show_player():

luke = Hero("Luke", "Mage")
luke.show_player()

Run our code again:

Player Name: Luke
Player Type: Mage

Our code runs successfully! We’ve first declared a variable called “luke” which stores information about a player called Luke. Luke’s player type is “Mage”. Now that we have instantiated that object, we can call the show_player() method.

Cause #2: Incorrectly Instantiating a Class

The “missing 1 required positional argument: ‘self’” error can occur when you incorrectly instantiate a class. Consider the following code:

luke = Hero
luke.show_player()

While this code is similar to our solution from the last example, it is incorrect. This is because we have not added any parenthesis after the word Hero. By missing these parentheses, our program does not know that we want to instantiate a class.

Solve this problem by adding parenthesis after Hero and specifying the required arguments, “name” and “player_type”:

luke = Hero("Luke", "Mage")
luke.show_player()

Our code now runs successfully and returns information about our player:

Player Name: Luke
Player Type: Mage

Conclusion

The “missing 1 required positional argument: ‘self’” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.

To solve this error, make sure that you first instantiate an object of a class before you try to access any of that class’ methods. Then, check to make sure you use the right syntax to instantiate an object.

Now you’re ready to solve this common error like an expert Python developer!

  1. Not Instantiating an Object in Python
  2. Incorrectly Instantiating a Class Object in Python
  3. Fix the TypeError: missing 1 required positional argument: 'self' Error in Python
  4. Conclusion

Python TypeError: Missing 1 Required Positional Argument

Classes are one of the fundamental features of Object-Oriented Programming languages. Every object belongs to some class in Python.

We can create our class as a blueprint to create objects of the same type. We use the class keyword to define a class in Python.

A very important feature in Python is using the self attribute while defining classes. The self attribute represents the object’s data and binds the arguments to the object.

This tutorial will discuss the TypeError: missing 1 required positional argument: 'self' error in Python and how we can solve it.

Let us discuss the situations where this error is raised.

Not Instantiating an Object in Python

Positional arguments refer to the data we provide a function with. For creating class objects, we use a constructor.

If the class requires any data, we must pass it as arguments in the constructor function.

This error is raised when we forget to instantiate the class object or wrongly instantiate the class instance.

See the code below.

class Delft:
   def __init__(self, name):
       self.name = name
   def fun(self):
       return self.name

m = Delft.fun()
print(m)

Output:

TypeError: fun() missing 1 required positional argument: 'self'

In the above example, we get the error because we forget to instantiate the instance of the class and try to access the function of the class. As a result, the self attribute is not defined and cannot bind the attributes to the object.

Note that this is a TypeError, which is raised in Python while performing some unsupported operation on a given data type. It is not supported to directly access the class method without creating an instance.

Incorrectly Instantiating a Class Object in Python

Another scenario where this error can occur is when we incorrectly instantiate the class object. This can be a small typing error like ignoring the parentheses or not providing the arguments.

For example:

class Delft:
   def __init__(self, name):
       self.name = name
   def fun(self):
       return self.name

m = Delft
a = m.fun()
print(a)

Output:

TypeError: fun() missing 1 required positional argument: 'self'

Let us now discuss how to fix this error in the section below.

Fix the TypeError: missing 1 required positional argument: 'self' Error in Python

To fix this error, we can create the class instance and use it to access the class method.

See the code below.

class Delft:
   def __init__(self, name):
       self.name = name
   def fun(self):
       return self.name

m = Delft('Stack')
a = m.fun()
print(a)

Output:

In the example, we first create an instance of the class. This is then used to access the class method to return some value and print it; the error is fixed.

Another fix involves the use of static methods. Static methods are functions bound to a particular class and not to an object.

We can use the @staticmethod decorator to create such methods.

For example:

class Delft:
   def __init__(self, name):
       self.name = name
   @staticmethod
   def fun(abc):
       return abc

a = Delft.fun('Stack')
print(a)

Output:

In the above example, we changed the fun() function to a static function. This way, we could use it without instantiating any class objects.

Conclusion

This tutorial discussed the TypeError: missing 1 required positional argument: 'self' error in Python and how we can solve it.

We discussed situations where this error might occur and how to fix the error by instantiating the object of the class. We can also use static methods to work around this error.

I can’t get past the error:

Traceback (most recent call last):
  File "C:UsersDomDesktoptesttest.py", line 7, in <module>
    p = Pump.getPumps()
TypeError: getPumps() missing 1 required positional argument: 'self'

I examined several tutorials but there doesn’t seem to be anything different from my code. The only thing I can think of is that Python 3.3 requires different syntax.

class Pump:

    def __init__(self):
        print("init") # never prints

    def getPumps(self):
        # Open database connection
        # some stuff here that never gets executed because of error
        pass  # dummy code

p = Pump.getPumps()

print(p)

If I understand correctly, self is passed to the constructor and methods automatically. What am I doing wrong here?

Kai - Kazuya Ito's user avatar

asked Jul 8, 2013 at 19:21

DominicM's user avatar

You need to instantiate a class instance here.

Use

p = Pump()
p.getPumps()

Small example —

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

gl393's user avatar

gl393

3013 silver badges14 bronze badges

answered Jul 8, 2013 at 19:23

Sukrit Kalra's user avatar

Sukrit KalraSukrit Kalra

32.2k7 gold badges66 silver badges70 bronze badges

0

You need to initialize it first:

p = Pump().getPumps()

answered Jul 8, 2013 at 19:23

JBernardo's user avatar

JBernardoJBernardo

31.6k10 gold badges89 silver badges114 bronze badges

0

Works and is simpler than every other solution I see here :

Pump().getPumps()

This is great if you don’t need to reuse a class instance. Tested on Python 3.7.3.

answered May 18, 2019 at 9:50

Jay D.'s user avatar

Jay D.Jay D.

1,2323 gold badges15 silver badges26 bronze badges

1

The self keyword in Python is analogous to this keyword in C++ / Java / C#.

In Python 2 it is done implicitly by the compiler (yes Python does compilation internally).
It’s just that in Python 3 you need to mention it explicitly in the constructor and member functions. example:

class Pump():
    # member variable
    # account_holder
    # balance_amount

    # constructor
    def __init__(self,ah,bal):
        self.account_holder = ah
        self.balance_amount = bal

    def getPumps(self):
        print("The details of your account are:"+self.account_number + self.balance_amount)

# object = class(*passing values to constructor*)
p = Pump("Tahir",12000)
p.getPumps()

Ghost Ops's user avatar

Ghost Ops

1,6902 gold badges12 silver badges23 bronze badges

answered Feb 19, 2019 at 13:21

Tahir77667's user avatar

Tahir77667Tahir77667

2,11816 silver badges15 bronze badges

4

You can call the method like pump.getPumps(). By adding @classmethod decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.

class Pump:

def __init__(self):
    print ("init") # never prints

@classmethod
def getPumps(cls):
            # Open database connection
            # some stuff here that never gets executed because of error

So, simply call Pump.getPumps() .

In java, it is termed as static method.

answered Sep 4, 2020 at 9:23

Atom's user avatar

AtomAtom

2306 silver badges13 bronze badges

1

You can also get this error by prematurely taking PyCharm’s advice to annotate a method @staticmethod. Remove the annotation.

answered Dec 3, 2017 at 15:58

gherson's user avatar

ghersongherson

1392 silver badges9 bronze badges

I got the same error below:

TypeError: test() missing 1 required positional argument: ‘self’

When an instance method had self, then I called it directly by class name as shown below:

class Person:
    def test(self): # <- With "self" 
        print("Test")

Person.test() # Here

And, when a static method had self, then I called it by object or directly by class name as shown below:

class Person:
    @staticmethod
    def test(self): # <- With "self" 
        print("Test")

obj = Person()
obj.test() # Here

# Or

Person.test() # Here

So, I called the instance method with object as shown below:

class Person:
    def test(self): # <- With "self" 
        print("Test")

obj = Person()
obj.test() # Here

And, I removed self from the static method as shown below:

class Person:
    @staticmethod
    def test(): # <- "self" removed 
        print("Test")

obj = Person()
obj.test() # Here

# Or

Person.test() # Here

Then, the error was solved:

Test

In detail, I explain about instance method in my answer for What is an «instance method» in Python? and also explain about @staticmethod and @classmethod in my answer for @classmethod vs @staticmethod in Python.

answered Nov 15, 2022 at 15:19

Kai - Kazuya Ito's user avatar

Kai — Kazuya ItoKai — Kazuya Ito

14.5k9 gold badges86 silver badges98 bronze badges

If skipping parentheses for the object declaration (typo), then exactly this error occurs.

# WRONG! will result in TypeError: getPumps() missing 1 required positional argument: 'self'
p = Pump
p.getPumps()

Do not forget the parentheses for the Pump object

# CORRECT!
p = Pump()
p.getPumps()

answered Nov 21, 2022 at 9:52

Daniel Nelson's user avatar

Daniel NelsonDaniel Nelson

1,6781 gold badge11 silver badges11 bronze badges

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

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

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

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Mise 605 indesit коды ошибок
  • Mirrors edge ошибка при запуске приложения 0xc0000906