Python骚操作:动态定义函数
标题:Python Tips: Dynamic function definition 作者:Philip Trauner 译者:豌豆花下猫 链接:https://philip-trauner.me/blog/post/python-tips-dynamic-function-definition 基于 MIT 许可协议 在 Python 中,没有可以在运行时简化函数定义的语法糖。然而,这并不意味着它就不可能,或者是难以实现。 from types import FunctionType foo_code = compile('def foo(): return "bar"', "<string>", "exec") foo_func = FunctionType(foo_code.co_consts[0], globals(), "foo") print(foo_func()) 输出: bar 剖析 逐行检视代码,你会发现语言/解释器的屏障是多么脆弱。 >>> from types import FunctionType Python 文档通常不会列出那...


