pythonconstructortypeerrorpositional-argument

Why do I get "TypeError: Missing 1 required positional argument: 'self'"?


I have some code like:

class Pump:    
    def __init__(self):
        print("init")

    def getPumps(self):
        pass

p = Pump.getPumps()
print(p)

But I get an error like:

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'

Why doesn't __init__ seem to be called, and what does this exception mean? My understanding is that self is passed to the constructor and methods automatically. What am I doing wrong here?


See Why do I get 'takes exactly 1 argument (2 given)' when trying to call a method? for the opposite problem.


Solution

  • To use the class, first create an instance, like so:

    p = Pump()
    p.getPumps()
    

    A full example:

    >>> class TestClass:
    ...     def __init__(self):
    ...         print("init")
    ...     def testFunc(self):
    ...         print("Test Func")
    ... 
    >>> testInstance = TestClass()
    init
    >>> testInstance.testFunc()
    Test Func