ChatGPT解决这个技术问题 Extra ChatGPT

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

我无法克服错误:

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 会自动传递给构造函数和方法。我在这里做错了什么?


g
gl393

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

利用

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

J
JBernardo

你需要先初始化它:

p = Pump().getPumps()

J
Jay D.

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

Pump().getPumps()

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


这实际上是 JBernardo's answer 的副本。请注意,他也不会保存实例,除非 getPumps() 返回 self,这很奇怪。
G
Ghost Ops

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

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

这不是一个关键字,只是一个约定。
“在 Python 2 中它是由编译器隐式完成的” 是什么意思? AFAIK Python 2 从未隐式设置 self
这不是有效的 Python 代码。你想确切地证明什么?首先,Python 注释使用 #,而不是 //;您不需要在类级别声明成员属性;那些管道似乎不合适。
“在 Python 2 中,它是由编译器隐式完成的”需要引用。
g
gherson

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


A
Atom

您可以调用 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方法。