小编jas*_*onh的帖子

记住在Python 3.6上有效但在3.7.3上无效的方法

我使用装饰器将通过lru_cache的备注扩展到本身不是可哈希的对象的方法(跟随stackoverflow.com/questions/33672412/python-functools-lru-cache-with-class-methods-release-object)。该备忘录可在python 3.6上正常运行,但在python 3.7上显示出意外的行为。

观察到的行为: 如果使用关键字参数调用备注方法,则备注在两个python版本上均能正常工作。如果在不使用关键字arg语法的情况下调用它,则它适用于3.6,但不适用于3.7。

==>是什么导致不同的行为?

下面的代码示例显示了一个重现此行为的最小示例。

test_memoization_kwarg_call通过python 3.6和3.7。 test_memoization_arg_call适用于python 3.6,但适用于3.7。

import random
import weakref
from functools import lru_cache


def memoize_method(func):
    # From stackoverflow.com/questions/33672412/python-functools-lru-cache-with-class-methods-release-object
    def wrapped_func(self, *args, **kwargs):
        self_weak = weakref.ref(self)

        @lru_cache()
        def cached_method(*args_, **kwargs_):
            return func(self_weak(), *args_, **kwargs_)

        setattr(self, func.__name__, cached_method)
        print(args)
        print(kwargs)
        return cached_method(*args, **kwargs)

    return wrapped_func


class MyClass:
    @memoize_method
    def randint(self, param):
        return random.randint(0, int(1E9))


def test_memoization_kwarg_call():
    obj = MyClass()
    assert obj.randint(param=1) == obj.randint(param=1)
    assert obj.randint(1) == obj.randint(1)


def test_memoization_arg_call():
    obj = …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-3.6 python-3.7

13
推荐指数
1
解决办法
359
查看次数

标签 统计

python ×1

python-3.6 ×1

python-3.7 ×1

python-3.x ×1