ctrlmaniac
ctrlmaniac

Reputation: 444

Call a function passed inside a list which is inside a class

I am a novice in Python and I was trying to program a game like Adventure.

I created a class called Room. In this class there is a function called ask_something in which I can pass a question and as many list as I want for the possible answers. Lists contain the possible answer and the effect of that answer which is another function.

How can I call that function whithin the Room class without knowing what function is it?

this is the code:

class Room:
    def ask_question(self, *arg):
        self.question = arg[0]
        self.answer_options = arg[1:]

        for option in self.answer_options:
            print '[{}] {}'.format(self.answer_options.index(option), option[0])

        answer = raw_input('> ')

        self.answer_options[int(answer)][1]()

def print_this(text):
    print text

Room.ask_question(
    'How are you?',
    ('Fine!', print_this('ok')),
    ('Not fine!', print_this('I\'m sorry'))
)

The Python console says

File "room.py", line 13, in ask_question
    do_something = self.answer_options[int(answer)][1]()
TypeError: 'NoneType' object is not callable

Upvotes: 0

Views: 42

Answers (1)

snapshoe
snapshoe

Reputation: 14264

You are executing/calling the print_this function and passing the return value of executing the function rather than passing the function itself. Also, you're not creating an instance of the Room class-- you're calling ask_question as a static method.

What you want is something like this:

Room().ask_question(
    'How are you?',
    ('Fine!', print_this, ('ok',)),
    ('Not fine!', print_this, ('I\'m sorry',))
)

def ask_question(self, *arg):
    #... some logic missing... need to handle looping through `arg` here
    # but as an example...
    # first arg is the first tuple-- ('Fine!', print_this, ('ok',))
    # 2nd element of this tuple is the print_this function
    # 3rd element of this tuple are the args to pass to the function
    do_something = arg[1][1]
    do_something_args = arg[1][2]

    do_something(*do_something_args)

Upvotes: 1

Related Questions