Coder Perfect

TypeError: One of the required positional arguments is missing: ‘self’

Problem

I’m stuck on the following error:

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

I looked through various tutorials but couldn’t find anything that differed from my code. The only thing that comes to mind is that Python 3.3 has a 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 my understanding is correct, self is automatically provided to the constructor and functions. I’m not sure what I’m doing wrong here.

Asked by DominicM

Solution #1

You must create a class instance in this case.

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

Answered by Sukrit Kalra

Solution #2

You must first initialize it:

p = Pump().getPumps()

Answered by JBernardo

Solution #3

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

Pump().getPumps()

If you don’t need to reuse a class instance, this is a fantastic option. Python 3.7.3 was used for testing.

Answered by Jay D.

Solution #4

In Python, the self keyword is similar to the self keyword in C++, Java, and 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()

Answered by Tahir77667

Solution #5

You can also get this error if you follow PyCharm’s recommendations and annotate a method with @staticmethod too soon. Remove the annotation from the document.

Answered by gherson

Post is based on https://stackoverflow.com/questions/17534345/typeerror-missing-1-required-positional-argument-self