从类实例调用exec()中的函数(Invoking functions within exec() from a class instance)

编程入门 行业动态 更新时间:2024-10-27 07:21:26
从类实例调用exec()中的函数(Invoking functions within exec() from a class instance)

我有一个自动生成的Python代码片段,我想在类实例中exec() 。

简化的代码段如下所示:

prog = """ def func1(): func2() def func2(): pass func1() """ class test(): def run(self): exec(prog) test().run() # results in NameError: name 'func2' is not defined exec(prog) # works

虽然在两种情况下都可以调用func1() ,但是当从类中exec()时,找不到func2 。 如果我先运行exec(prog) ,那么即使是test().run()也会成功。 似乎前面的exec调用将func2留在命名空间中的某个位置,以后可以在类中调用它时找到它。

是否有一种简单而干净的方法来调用包含类中几个函数的代码片段?

I have an auto-generated Python code snippet which I'd like to exec() from within a class instance.

A simplified snippet looks like this:

prog = """ def func1(): func2() def func2(): pass func1() """ class test(): def run(self): exec(prog) test().run() # results in NameError: name 'func2' is not defined exec(prog) # works

While func1() can be called in both cases, func2 isn't found when exec()'ing from within the class. If I run the exec(prog) first, then even the test().run() succeeds. It seems that the previous exec call left func2 at some place in the namespace where it can later be found when called from within the class.

Is there a simple and clean way to call such a code snippet containing several functions from within a class?

最满意答案

您可以使用exec(prog, globals())来执行全局命名空间中的代码。

You can use exec(prog, globals()) to execute the code in the global namespace.

更多推荐

本文发布于:2023-08-06 12:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1448652.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   实例   exec   Invoking   class

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!