1

我将一个函数动态传递给另一个类,如下所示

    class simulator(object):
        def __init__(self, fn_):

            print(self.test(fn_))


        def test(self, fn):
            return  fn(self, 20)


    class t(object):

        s = 'def get_fitness(x, y):\n return x+y'

        exec(s)

        def fnGetFitness(self,genes):
            return get_fitness(genes, 10)

        simulator(fnGetFitness)



    t()

但我面临以下错误:

    File "N:/Job/GA/mine/dyn.py", line 25, in fnGetFitness
          return get_fitness(genes, 10)

    NameError: name 'get_fitness' is not defined

我猜它与范围有关,但我无法处理任何人?

编辑 :

这是一个更简单的代码,显示了问题:

    class t(object):
        def __init__(self):
            exec('def get_fitness(x, y):\n return x+y')
            print(get_fitness(2,3))
    t()
4

1 回答 1

1

无关exec。您正在做的事情等同于(删除了安全性):

class t(object):
    def get_fitness(x,y):
        return x+y

但是您的方法定义是在类级别,而不是在simulator类上。

simulator(fnGetFitness)调用fnGetFitnesst上下文,所以它不知道你的新函数。

那行不通(也get_fitness应该被装饰为@staticmethod因为它没有self参数)

有效的是在全局级别动态(或不)定义函数,以便类可以调用它

s = 'def get_fitness(x, y):\n return x+y'
exec(s)

class t(object):
    def fnGetFitness(self,genes):
        return get_fitness(genes, 10)

    simulator(fnGetFitness)

t()

解决了它,但老实说,我对目的感到困惑(我已经花了一段时间来弄清楚如何从你的代码中运行某些东西)

编辑:评论中发布了一个更简单且在某种程度上不同(和exec相关)的代码:

class t(object):
    def __init__(self):
        exec('def get_fitness(x, y):\n return x+y')
        print(get_fitness(2,3))
t()

这引起了NameError: name 'get_fitness' is not defined

现在这与exec. 什么时候__init__被解析,get_fitness是未知的,因为解析器没有把它看作一个局部变量,即使在执行的时候,它是在locals()字典中设置的exec(相关:为什么'ord'在这里被看作一个未分配的变量?)。

一种解决方法是在局部变量中获取函数,如下所示:

class t(object):
    def __init__(self):
        exec('def get_fitness(x, y):\n return x+y')
        print(locals()["get_fitness"](2,3))

t()

这工作和打印5

于 2018-10-21T08:06:54.530 回答