나는 파이썬을 처음 접했고 벽에 부딪쳤다. 몇 가지 자습서를 수행했지만 오류를 벗어날 수 없습니다.
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'
몇 가지 자습서를 검토했지만 내 코드와 다른 것으로 보이지 않습니다. 내가 생각할 수있는 유일한 것은 파이썬 3.3에 다른 구문이 필요하다는 것입니다.
메인 scipt :
# test script
from lib.pump import Pump
print ("THIS IS A TEST OF PYTHON") # this prints
p = Pump.getPumps()
print (p)
펌프 등급 :
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
올바르게 이해하면 “self”가 생성자와 메소드에 자동으로 전달됩니다. 내가 여기서 뭘 잘못하고 있니?
파이썬 3.3.2에서 Windows 8을 사용하고 있습니다.
답변
여기에서 클래스 인스턴스를 인스턴스화해야합니다.
사용하다
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()
클래스 인스턴스를 재사용 할 필요가없는 경우에 좋습니다. 파이썬 3.7.3에서 테스트되었습니다.
답변
@staticmethod 메소드에 주석을 달기 위해 PyCharm의 조언을 조기에 가져 와서이 오류를 얻을 수도 있습니다. 주석을 제거하십시오.
답변
파이썬 의 ‘self’ 키워드 는 c ++ / java / c #의 ‘this’ 키워드와 유사합니다 .
파이썬 2에서는 컴파일러에 의해 암시 적으로 수행됩니다 (yes python does compilation internally)
. 파이썬 3 explicitly
에서는 생성자 및 멤버 함수에서 언급해야 합니다. 예:
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()
답변
