TypeError:缺少1个必需的位置参数:'self'


217

我是python新手,碰壁了。我遵循了一些教程,但无法克服错误:

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'

我检查了一些教程,但似乎与我的代码没有什么不同。我唯一能想到的是python 3.3需要不同的语法。

主要技巧:

# test script

from lib.pump import Pump

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

p = Pump.getPumps()

print (p)

泵类:

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

如果我正确理解,“自我”将自动传递给构造函数和方法。我在这里做错了什么?

我正在将Windows 8与python 3.3.2一起使用

Answers:


280

您需要在此处实例化一个类实例。

p = Pump()
p.getPumps()

小例子-

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

1
之前曾尝试过,但缺少“()”。这是python 3.x中的新功能吗?
DominicM

1
@DominicM:不,一直存在。
Sukrit Kalra

1
是的,回想一下我所遵循的教程,我的大脑一定刚刚把括号

4
类名应为大写,即“ testClass”应为“ TestClass”
eggonlegs 2014年

1
谢谢,在类实例化上缺少括号是我的问题。您的例子非常清楚。
保罗·沃森

57

您需要先对其进行初始化:

p = Pump().getPumps()

14
简单性常常被低估。
theeastcoastwest

14
这样做会使p等于方法getPumps(),而运行p则不能作为Pump()类的变量“使用”。imo并不是一个好习惯,因为它只是创建一个无用的变量。如果唯一的目标是运行getPumps函数,则仅运行Pump()。getPumps()而不是为该函数创建变量即可。
Ashmoreinc

7

比我在这里看到的所有其他解决方案都有效并且更简单:

Pump().getPumps()

如果您不需要重用类实例,那么这很好。在Python 3.7.3上测试。


2

您也可以通过过早地接受PyCharm的建议来注释方法@staticmethod来获得此错误。删除注释。


1

python中的'self'关键字类似于c ++ / java / c#中的'this'关键字。

在python 2中,它是由编译器隐式完成的(yes python does compilation internally)。只是在python 3中,您需要explicitly在构造函数和成员函数中提及它。例:

 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()
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.