当我阅读 Python 的 collections 模块 ( http://hg.python.org/cpython/file/2.7/Lib/collections.py#l234 ) 的源代码时,我发现 namedtuple 函数从一个字符串模板创建了一个类的定义,它是用 exec 执行。为什么不像在编写装饰器时那样简单地在函数内部定义一个类来完成呢?在我看来,它会是更具可读性和更可靠的解决方案,不是吗?我敢打赌 Python 核心开发人员知道他们在做什么,那么我在这里错过了什么?
请您参考如下方法:
Raymond Hettinger 在他的 original ActiveState recipe 中简要提到了这一点:
Thanks to Peter Kovac pointing-out deficiencies in the keyword argument checking. Because of his comments, the recipe has evolved to its current exec-style where we get all of Python's high-speed builtin argument checking for free. The new style of building and exec-ing a template made both the
__new__and__repr__functions faster and cleaner than in previous versions of this recipe.
