我不能忽略这个错误:
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需要不同的语法。
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
会自动传递给构造函数和方法。我在这里做错了什么?
发布于 2013-07-09 03:23:06
你需要在这里实例化一个类实例。
使用
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-09 03:23:11
您需要先初始化它:
p = Pump().getPumps()
发布于 2019-05-18 17:50:49
比我在这里看到的任何其他解决方案都有效,也更简单:
Pump().getPumps()
如果你不需要重用一个类实例,这是很棒的。在Python 3.7.3上测试。
https://stackoverflow.com/questions/17534345
复制相似问题