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

Dom*_*icM 168 python python-3.x

我是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'
Run Code Online (Sandbox Code Playgroud)

我检查了几个教程,但似乎与我的代码没有任何不同.我唯一能想到的是python 3.3需要不同的语法.

主要内容:

# test script

from lib.pump import Pump

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

p = Pump.getPumps()

print (p)
Run Code Online (Sandbox Code Playgroud)

泵类:

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
Run Code Online (Sandbox Code Playgroud)

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

我使用的是Windows 8和python 3.3.2

Suk*_*lra 209

您需要在此实例化一个类实例.

使用

p = Pump()
p.getPumps()
Run Code Online (Sandbox Code Playgroud)

小例子 -

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


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func
Run Code Online (Sandbox Code Playgroud)

  • 类名应为大写,即“ testClass”应为“ TestClass” (3认同)
  • 之前尝试过,但缺少“()”。这是python 3.x中的新功能吗? (2认同)
  • @DominicM:不,它一直存在。 (2认同)
  • 是的,回顾我遵循的教程,我的大脑一定只是把括号涂黑了:) (2认同)

JBe*_*rdo 41

您需要先将其初始化:

p = Pump().getPumps()
Run Code Online (Sandbox Code Playgroud)

  • 这样做会使p等于方法getPumps(),而这将运行p不会'可用'作为Pump()类的变量.这不是很好的实践,因为它只是创造一个无用的变量.如果唯一的目标是运行getPumps函数,那么只运行Pump().getPumps()而不是为函数创建变量. (10认同)
  • 简单性通常被低估. (8认同)

Jay*_* D. 12

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

Pump().getPumps()
Run Code Online (Sandbox Code Playgroud)

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


Ato*_*tom 11

向该方法添加@classmethod装饰器允许像Pump.getPumps().

类方法接收类作为隐式第一个参数,就像实例方法接收实例一样。

class Pump:
    def __init__(self):
        print("init")

    @classmethod
    def getPumps(cls):
        pass
Run Code Online (Sandbox Code Playgroud)


Tah*_*667 8

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()
Run Code Online (Sandbox Code Playgroud)

  • *“在 Python 2 中,它是由编译器隐式完成的”* 是什么意思?AFAIK Python 2 从不隐式设置 `self`。 (4认同)
  • 它不是一个关键字,只是一个约定。 (3认同)
  • *“在 Python 2 中,它是由编译器隐式完成的”* 需要引用。 (2认同)

ghe*_*son 6

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