python类调用需要我发送self,SpeechEngine.test\u选项(SpeechEngine)
我遇到了一些问题,每当我调用我的一个类方法时,它都要求我专门发送包含该调用的类,我希望它自己已经知道它。我确信这是用户错误,但无法跟踪它 我已经提到了,但我想我已经涵盖了python类调用需要我发送self,SpeechEngine.test\u选项(SpeechEngine),python,oop,self,Python,Oop,Self,我遇到了一些问题,每当我调用我的一个类方法时,它都要求我专门发送包含该调用的类,我希望它自己已经知道它。我确信这是用户错误,但无法跟踪它 我已经提到了,但我想我已经涵盖了 class SpeechEngine(): def __init__(self): self.conn = sqlite3.connect('../twbot.db') self.c = self.conn.cursor() @staticmethod def choose(choice): num
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')
因为initial_contact_msg是一个方法,所以需要从实例而不是类型调用它。你最后一次尝试几乎是对的。要实例化它,您需要执行以下操作:
test = SpeechEngine()
test.initial_contact_msg(0, 'sometime')
“SpeechEngine”是类型类。创建新实例时,需要像调用函数一样调用它。这类似于在其他语言中使用“new”关键字
使用静态方法时,可以直接从类型对象调用:
SpeechEngine.choose()
您可以在中阅读更多信息。您可能希望创建
SpeechEngine
的实例SpeechEngine=SpeechEngine()
然后调用SpeechEngine
Aha上的方法,在上一个示例中,您缺少测试=SpeechEngine
上的()
。如果最后没有()
,您只需将类绑定到另一个名称,而不是创建一个实例感谢帮助,这确实是个问题!