不能使用字典中的函数

时间:2015-08-18 19:44:59

标签: python

我正在尝试使用带有函数值的字典,但是

NameError: name 'oak' is not defined

在显示任何其他内容之前停止执行。

这是调度员的类:

from hab_oak import Oak
from pokemon import Pokemon
from hab_brock import GimnasioBrock

class Juego(object):

    habs = {
        'Oak' : oak  
    }

    def __init__(self):
        oak = Oak()
        maproom, pok = oak.execution()
        self.Pokemon = pok
        dispatcher(Juego.habs.get(maproom), self.Pokemon)


    def dispatcher(command, arg):
        send(habs[command](arg))


    def oak(self, pokemon):
        GimnasioBrock(pokemon)

我很确定下一个类Oak不是给出错误的那个,但它是在Juego中实例化的那个。 init

from sys import exit
from random import randint
from pokemon import Pokemon
from hab_brock import GimnasioBrock

class Oak(object):

    def execution(self):
        print "Bienvenido, soy Oak. Elige un pokemon."
        print "Puedes elegir Charmander, Squirtle o Bulbasaur:"

        pokemon_elegido = raw_input("> ")

        if (pokemon_elegido == "Charmander"):
            pokemon = Pokemon("Charmander", 20, 5)
        elif (pokemon_elegido == "Bulbasaur"):
            pokemon = Pokemon("Bulbasaur", 20, 5)
        elif(pokemon_elegido == "Squirtle"):
            pokemon = Pokemon("Squirtle", 20, 5)

        print "Te enfrentaras a Brock."

        return "Oak", pokemon

1 个答案:

答案 0 :(得分:1)

在类定义函数之前,您要将字典值设置为函数。如果要将函数存储在类变量中,请将oak()更改为静态方法,或将函数设置为__init__()

中的值

静态方法示例:

class Juego(object):

    habs = {
        'Oak' : Juego.oak()  
    }

    @staticmethod
    def oak(pokemon):
        GimnasioBrock(pokemon)

Init示例:

class Juego(object):

    habs = {}

    def __init__(self):
        oak = Oak()
        maproom, pok = oak.execution()
        self.Pokemon = pok
        dispatcher(Juego.habitaciones.get(maproom), self.Pokemon)
        self.habs.update({'Oak':self.oak})

    def oak(self, pokemon):
        GimnasioBrock(pokemon)