【问题标题】:need memoized function to quack like a function需要记忆函数才能像函数一样嘎嘎作响
【发布时间】:2012-06-25 18:54:18
【问题描述】:

在我的一些代码中,我使用了 Python 装饰器库中漂亮的 memoized 类。

我正在使用的库之一对函数使用自省来获取它需要的参数数量,但在装饰函数上失败。具体来说,它检查co_argcount 变量。

if (PyInt_AsLong(co_argcount) < 1) {
      PyErr_SetString(PyExc_TypeError, "This function has no parameters to mini\
mize.");

似乎 argcount 没有被转移到记忆函数中。

>>> def f(x):
...     return x
... 
>>> f.func_code.co_argcount
1
>>> g = memoized(f)
>>> g.func_code.co_argcount
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'memoized' object has no attribute 'func_code'

如何修改 memoized 类,使我的 memoized 函数看起来、尝起来和闻起来都像原始函数?

【问题讨论】:

    标签: python memoization


    【解决方案1】:

    您需要创建一个保留签名的装饰器。最简单的方法是使用库 http://pypi.python.org/pypi/decorator,它负责为您保留签名。

    该库的内部结构非常丑陋(它使用 exec!),但它很好地封装了它们。

    【讨论】:

      【解决方案2】:

      将其添加到您的 memoized 课程中

      def __getattr__(self, name):
          if name.startswith('func_'):
              return getattr(self.func, name)
          raise AttributeError
      

      所以它会将func_... 的属性查找传递给原始函数。

      也许您还想编写一个__setattr__ 函数来拒绝写入这些属性,但如果您知道您不会尝试更改这些值,则没有必要。

      【讨论】:

        猜你喜欢
        • 2015-07-03
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-06
        • 1970-01-01
        • 2014-03-17
        • 1970-01-01
        相关资源
        最近更新 更多