调用在类中的列表内传递的函数

时间:2015-05-31 02:05:32

标签: python function class

我是Python的新手,我正在尝试编写像Adventure这样的游戏。

我创建了一个名为Room的类。在这个类中有一个名为ask_something的函数,我可以在其中传递一个问题和尽可能多的列表,以获得可能的答案。列表包含可能的答案以及该答案的效果,这是另一个功能。

如何在Room类中调用该函数而不知道它是什么函数?

这是代码:

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'))
)

Python控制台说

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

1 个答案:

答案 0 :(得分:1)

您正在执行/调用print_this函数并传递执行函数的返回值,而不是传递函数本身。 此外,您没有创建Room类的实例 - 您将ask_question称为静态方法。

你想要的是这样的:

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)