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)
JBe*_*rdo 41
您需要先将其初始化:
p = Pump().getPumps()
Run Code Online (Sandbox Code Playgroud)
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)
Python 中的关键字self
类似于this
C++ / 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)
归档时间: |
|
查看次数: |
575880 次 |
最近记录: |