339

我无法克服错误:

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 需要不同的语法。

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()

print(p)

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

4

6 回答 6

443

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

利用

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
于 2013-07-08T19:23:06.457 回答
83

你需要先初始化它:

p = Pump().getPumps()
于 2013-07-08T19:23:10.783 回答
13

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

Pump().getPumps()

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

于 2019-05-18T09:50:49.080 回答
5

Python 中的self关键字类似于thisC++/Java/C# 中的关键字。

在 Python 2 中,它由编译器隐式完成(是的,Python 在内部进行编译)。只是在 Python 3 中需要在构造函数和成员函数中明确提及。例子:

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()
于 2019-02-19T13:21:34.470 回答
3

您还可以通过过早采用 PyCharm 的建议来注释方法 @staticmethod 来获得此错误。删除注释。

于 2017-12-03T15:58:11.320 回答
2

您可以调用类似的方法pump.getPumps()。通过在方法上添加@classmethod装饰器。类方法接收类作为隐式第一个参数,就像实例方法接收实例一样。

class Pump:

def __init__(self):
    print ("init") # never prints

@classmethod
def getPumps(cls):
            # Open database connection
            # some stuff here that never gets executed because of error

所以,只需调用Pump.getPumps().

在java中,它被称为static方法。

于 2020-09-04T09:23:30.917 回答