TypeError: Missing 1 required positional argument:

2018-12-31 15:18发布

问题:

I am new to python and have hit a wall. I followed several tutorials but cant get past the 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 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.

main scipt:

# test script

from lib.pump import Pump

print (\"THIS IS A TEST OF PYTHON\") # this prints

p = Pump.getPumps()

print (p)

Pump class:

import pymysql

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

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

I am using windows 8 with python 3.3.2

回答1:

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


回答2:

You need to initialize it first:

p = Pump().getPumps()


回答3:

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



回答4:

I had a similar problem. A piece of my code looked like this:

class player(object):
    def update(self):
        if self.score == game.level:
            game.level_up()

class game(object):
    def level_up(self):
        self.level += 1

It also gave me that error about missing self. I solved it by typing game.level_up(game) instead of game.level_up().

It should work for you too, but I\'m not sure if that\'s the reccomended way.