为什么我的代码错误?我在django.utils.functional中复制了'memoize'函数

时间:2010-01-06 09:00:19

标签: python django

我的代码:

a=[1,2,3,4]
b=a[:2]
c=[]
c[b]='sss'#error

memoize功能:

def memoize(func, cache, num_args):
    def wrapper(*args):
        mem_args = args[:num_args]#<------this
        if mem_args in cache:
            return cache[mem_args]
        result = func(*args)
        cache[mem_args] = result#<-----and this
        return result

2 个答案:

答案 0 :(得分:2)

memoize函数中,我假设cachedict。此外,由于a是list,b也将是list,并且列表不可清除。使用tuple

尝试

a = (1, 2, 3, 4) # Parens, not brackets
b = a[:2]
c = {} # Curly braces, not brackets
c[b] = 'sss'

答案 1 :(得分:2)

您的问题与您发布的memoize功能有什么关系?

据推测(虽然我们必须猜测,因为你没有发布实际的错误)你得到了一个TypeError。这是由于两个错误。

首先,c是一个列表。所以你不能使用任意键,你只能使用整数索引。大概你打算在这里定义一个字典:c = {}

其次,你在语句2中得到一个列表 - b等于[1, 2] - 这不是一个有效的字典索引。 a应该是一个元组:a = (1, 2, 3, 4)

我必须重申其他人给你的建议。在尝试复制您不理解的高级Python代码之前,请先查看编程并阅读它。