LPTHW ex。 45,如何从另一个模块中的类返回函数?

时间:2012-12-14 13:58:32

标签: python class module

尝试在Zed Shaw的LPTHW中为ex 45制作我自己的RPG角色生成器。部分任务是为该计划的每个“房间”创建一个新课程,例如WelcomeScreenChooseMutations

这是主程序。

import rooms

class Program(object):

    def __init__(self, start):
        self.start = start

    def run(self):
        next_room_name = self.start

        while True:
            room = getattr(self, next_room_name)
            next_room_name = room()

x = rooms.WelcomeRoom()

Program(x.hello_user())

以下是它试图从中提取内容的rooms文件。

class WelcomeRoom(object):

    def __init__(self):
        pass

    def hello_user(self):
        print '*' * 79
        print '\n'
        print '\t\tWelcome to the'
        print '\t\tMetamorphosis Alpha Character & Random Encounter Generator'
        print '\t\tProgrammed poorly by Raymond Weiss'
        print '\n'
        print '*' * 79
        raw_input('Please press enter to continue')
        return 'get_name'

    def get_name(self):

        name = raw_input('Hello, whats your name?', 
                 '\n',
                 ':> ')

但是当我在python中运行主程序时,它只是注销而不是从get_name()返回函数rooms。输出发布在下面。

Raymond-Weisss-MacBook-Pro:macgre Raylug$ python macgre.py
*******************************************************************************


        Welcome to the
        Metamorphosis Alpha Character & Random Encounter Generator
        Programmed poorly by Raymond Weiss


*******************************************************************************
Please press enter to continue
Raymond-Weisss-MacBook-Pro:macgre Raylug$ 

我提前道歉,如果我的问题标题不是我试图提出的问题,作为一个新手,它有时很难不知道究竟要问什么。

1 个答案:

答案 0 :(得分:1)

您将返回一个字符串,而不是函数(或函数结果)。你可能想要这样的东西:

def hello_user(self):
    return self.get_name

def hello_user(self):
    return self.get_name()

根据你的程序,我想你可能想要第二个。区别在于第一个返回get_name 函数,而第二个返回get_name函数的结果