为了账号安全,请及时绑定邮箱和手机立即绑定

python - 类调用需要我发送自我,SpeechEngine.test_choice

python - 类调用需要我发送自我,SpeechEngine.test_choice

芜湖不芜 2021-09-02 20:28:36
我遇到了一些问题,每当我调用我的一个类方法时,它要求我专门发送包含类的调用,我希望它已经知道它自己。我确定这是用户错误,但无法追踪。我已经引用了python - self - 必需的位置参数,但我想我已经涵盖了。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')但这会返回以下内容missing 1 required positional argument: 'self'好像我隐含地这样做SpeechEngine.initial_contact_msg(SpeechEngine, 0, 'somename')它不问任何问题就返回预期的结果。我还应该指出,当我将其分配如下时也会发生同样的情况。test = SpeechEnginetest.initial_contact_msg(0, 'somename')
查看完整描述

1 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

由于 initial_contact_msg 是一种方法,因此您需要从实例中调用它,而不是从类型中调用它。你的最后一次尝试几乎是正确的。要实例化它,您需要执行以下操作:


test = SpeechEngine()

test.initial_contact_msg(0, 'sometime')

“SpeechEngine”是类型类。创建新实例时,您需要像调用函数一样调用它。这类似于在其他语言中使用“new”关键字。


当您有一个静态方法时,可以直接从 Type 对象中调用它:


SpeechEngine.choose()

您可以在Python 文档 中阅读更多内容。


查看完整回答
反对 回复 2021-09-02
  • 1 回答
  • 0 关注
  • 136 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信