python类调用要求我发送self、SpeechEngine.test\u选项(SpeechEngine)

2024-09-29 01:39:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一些问题,每当我调用我的一个类方法时,它都要求我专门发送包含该调用的类,我希望它自己已经知道它。我确信这是用户错误,但无法跟踪它

我引用了python - self - required positional argument,但我想我已经涵盖了这一点

class SpeechEngine():

def __init__(self):
    self.conn = sqlite3.connect('../twbot.db')
    self.c = self.conn.cursor()

@staticmethod
def choose(choice):
    num_choices = len(choice)
    selection = random.randrange(0, num_choices)
    return selection

def 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 = SpeechEngine
test.initial_contact_msg(0, 'somename')

Tags: selfhellostringdefrequiredcontactmsgargument
1条回答
网友
1楼 · 发布于 2024-09-29 01:39:35

因为initial_contact_msg是一个方法,所以需要从实例而不是类型调用它。你最后一次尝试几乎是对的。要实例化它,您需要执行以下操作:

test = SpeechEngine()
test.initial_contact_msg(0, 'sometime')

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

使用静态方法时,可以直接从类型对象调用:

SpeechEngine.choose()

你可以在Python Documentation中阅读更多内容

相关问题 更多 >