我无法克服错误:
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
会自动传递给构造函数和方法。我在这里做错了什么?
您需要在此处实例化一个类实例。
利用
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()
如果您不需要重用类实例,这很好。在 Python 3.7.3 上测试。
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()
self
。
#
,而不是 //
;您不需要在类级别声明成员属性;那些管道似乎不合适。
您还可以通过过早采用 PyCharm 的建议来注释方法 @staticmethod 来获得此错误。删除注释。
您可以调用 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
方法。
getPumps()
返回self
,这很奇怪。