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

问题描述 投票:0回答:8

我有一些代码:

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

    def getPumps(self):
        pass

p = Pump.getPumps()
print(p)

但我收到如下错误:

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'

为什么

__init__
好像没有被调用,这个异常是什么意思?我的理解是
self
自动传递给构造函数和方法。我在这里做错了什么?

python python-3.x constructor self instance-methods
8个回答
540
投票

要使用该类,首先创建一个实例,如下所示:

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

97
投票

你需要先初始化它:

p = Pump().getPumps()

19
投票

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

Pump().getPumps()

如果您不需要重用类实例,这非常好。在 Python 3.7.3.

上测试

8
投票

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

8
投票

在方法中添加一个

@classmethod
装饰器允许像
Pump.getPumps()
一样调用它。

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

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

    @classmethod
    def getPumps(cls):
        pass

4
投票

你也可以通过过早地接受 PyCharm 的建议来注释方法 @staticmethod 来得到这个错误。删除注释。


1
投票

如果跳过对象声明的括号(拼写错误),则会发生此错误。

# WRONG! will result in TypeError: getPumps() missing 1 required positional argument: 'self'
p = Pump
p.getPumps()

不要忘记 Pump 对象的括号

# CORRECT!
p = Pump()
p.getPumps()

0
投票

我在下面遇到了同样的错误:

TypeError: test() missing 1 required positional argument: 'self'

一个实例方法

self
,那么我直接通过类名调用它如下所示:

class Person:
    def test(self): # <- With "self" 
        print("Test")

Person.test() # Here

而且,当一个静态方法

self
,然后我通过对象调用它或者直接通过类名调用它,如下所示:

class Person:
    @staticmethod
    def test(self): # <- With "self" 
        print("Test")

obj = Person()
obj.test() # Here

# Or

Person.test() # Here

所以,我用对象调用了实例方法,如下所示:

class Person:
    def test(self): # <- With "self" 
        print("Test")

obj = Person()
obj.test() # Here

并且,我从静态方法中删除了

self
,如下所示:

class Person:
    @staticmethod
    def test(): # <- "self" removed 
        print("Test")

obj = Person()
obj.test() # Here

# Or

Person.test() # Here

然后,错误解决了:

Test

详细地,我在我的答案中解释了实例方法什么是Python中的“实例方法”?并且还解释了@staticmethod@classmethodmy answer for@classmethod vs @staticmethod in Python.

© www.soinside.com 2019 - 2024. All rights reserved.