类型错误:缺少1个必需的位置参数:'self'

2024-04-25 05:39:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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'

我检查了几个教程,但似乎与我的代码没有什么不同。我唯一能想到的是Python3.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

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

我将windows 8与python 3.3.2结合使用


Tags: testimportselfmostinitdef错误教程
3条回答

你需要在这里实例化一个类实例。

使用

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

您需要先初始化它:

p = Pump().getPumps()

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

Pump().getPumps()

如果您不需要重用类实例,这将非常好。在Python3.7.3上测试。

相关问题 更多 >