TypeError: Missing 1 required positional argument: 'self'

I am new to python and hit the wall. I followed a few tutorials, but can not 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 studied a few tutorials, but it seems that something is not like my code. The only thing I can think of is that python 3.3 requires a 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, that "I" is automatically passed to the constructor and methods. What am I doing wrong here?

I am using Windows 8 with python 3.3.2

+127
python
Jul 08 '13 at 19:21
source share
6 answers

You need to instantiate the class here.

using

 p = Pump() p.getPumps() 

A small example is

 >>> class TestClass: def __init__(self): print("in init") def testFunc(self): print("in Test Func") >>> testInstance = TestClass() in init >>> testInstance.testFunc() in Test Func 
+161
Jul 08 '13 at 19:23
source share
— -

First you need to initialize it:

 p = Pump().getPumps() 
+34
Jul 08 '13 at 19:23
source share

You can also get this error by prematurely accepting PyCharm's recommendations to annotate the @staticmethod. Delete the annotation.

+2
Dec 03 '17 at 15:58
source share

The self keyword in python is similar to the this keyword in c ++ / java / C #.

In Python 2, this is done implicitly by the compiler (yes python does compilation internally) . Just in Python 3, you need to explicitly mention this 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() 
0
Feb 19 '19 at 13:21
source share

It works and is easier than any other solution that I see here:

 Pump().getPumps() 

This is great if you do not need to reuse the class instance. Tested in Python 3.7.3.

0
May 18 '19 at 9:50
source share

I had a similar problem. Part 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 an error about the lack of self . I solved this by typing game.level_up(game) instead of game.level_up() .

This should work for you too, but I'm not sure if this is the recommended way.

-one
May 30 '18 at 8:50
source share



All Articles