Coder Perfect

TypeError: Missing 1 required positional argument: ‘self’


I can’t get past the error:

Traceback (most recent call last):
  File "C:\Users\Dom\Desktop\test\", 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 me 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()


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.


p = Pump()

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

It works and is less complicated than any other solution I’ve seen thus far:


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

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

The compiler does that for you implicitly in Python 2. (yes Python does compilation internally). It’s just that you have to explicitly specify it in the constructor and member procedures in Python 3. 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)

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