我遇到了一些問(wèn)題,每當(dāng)我調(diào)用我的一個(gè)類方法時(shí),它要求我專門(mén)發(fā)送包含類的調(diào)用,我希望它已經(jīng)知道它自己。我確定這是用戶錯(cuò)誤,但無(wú)法追蹤。我已經(jīng)引用了python - self - 必需的位置參數(shù),但我想我已經(jīng)涵蓋了。class SpeechEngine():def __init__(self): self.conn = sqlite3.connect('../twbot.db') self.c = self.conn.cursor()@staticmethoddef choose(choice): num_choices = len(choice) selection = random.randrange(0, num_choices) return selectiondef initial_contact_msg(self, userId, screenName): hello = self.c.execute("SELECT text, id FROM speechConstructs WHERE type='salutation'").fetchall() tagline = self.c.execute("SELECT text, id FROM speechConstructs WHERE type='tagline'").fetchall() c1 = self.choose(hello) c2 = self.choose(tagline) msg_string = str(hello[c1][0]) + ' @' + screenName + ' ' + tagline[c2][0] # print(msg_string) # For Testing Only # print(hello[c1][1]) # For Testing Only return msg_string然后我希望打電話SpeechEngine.initial_contact_msg(0, 'somename')但這會(huì)返回以下內(nèi)容missing 1 required positional argument: 'self'好像我隱含地這樣做SpeechEngine.initial_contact_msg(SpeechEngine, 0, 'somename')它不問(wèn)任何問(wèn)題就返回預(yù)期的結(jié)果。我還應(yīng)該指出,當(dāng)我將其分配如下時(shí)也會(huì)發(fā)生同樣的情況。test = SpeechEnginetest.initial_contact_msg(0, 'somename')
1 回答

qq_花開(kāi)花謝_0
TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
由于 initial_contact_msg 是一種方法,因此您需要從實(shí)例中調(diào)用它,而不是從類型中調(diào)用它。你的最后一次嘗試幾乎是正確的。要實(shí)例化它,您需要執(zhí)行以下操作:
test = SpeechEngine()
test.initial_contact_msg(0, 'sometime')
“SpeechEngine”是類型類。創(chuàng)建新實(shí)例時(shí),您需要像調(diào)用函數(shù)一樣調(diào)用它。這類似于在其他語(yǔ)言中使用“new”關(guān)鍵字。
當(dāng)您有一個(gè)靜態(tài)方法時(shí),可以直接從 Type 對(duì)象中調(diào)用它:
SpeechEngine.choose()
您可以在Python 文檔 中閱讀更多內(nèi)容。
添加回答
舉報(bào)
0/150
提交
取消