Search code examples
pythonoopself

python - class calls require me to send self, SpeechEngine.test_choice(SpeechEngine)


I'm having some issues where whenever I make a call to one of my classes methods it's requiring me to specifically send the containing class with the call, where I would expect it to already know about it self. I'm sure this is user error but can not track it down.

I've referenced python - self - required positional argument but i think i've got that covered.

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

And then I would expect to call

SpeechEngine.initial_contact_msg(0, 'somename')

But that returns the following

missing 1 required positional argument: 'self'

Where as if i do it implicitly

SpeechEngine.initial_contact_msg(SpeechEngine, 0, 'somename')

It returns the expected results no questions asked. I should also point out the same happens when i would assign it as follows.

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

Solution

  • Since initial_contact_msg is a method, you need to call it from an instance, not the Type. Your last attempt is almost right. To instantiate it, you need to do the following:

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

    "SpeechEngine" is the type class. When you create a new instance you need to call it like a function. This is similar to using the "new" keyword in other languages.

    When you have a static method, this can be called directly from the Type object:

    SpeechEngine.choose()
    

    You can read more in the Python Documentation.