首页 > 解决方案 > Python:装饰器+列表理解-TypeError:'int'对象不可迭代

问题描述

我试图返回一个除以 2 的列表以获得列表中的偶数。我正在尝试使用装饰器执行此操作,但出现错误TypeError: 'int' object is not iterable

我的代码是

def getEven(fnc): 
    def inner(list_of_val):
        return [ devideBy2(int(value)) for value in list_of_val ]
    return inner

@getEven
def devideBy2(num):
    return int(num)/2

list_of_num = [ 1, 2, 3, 4, 5]

print(devideBy2(list_of_num))

当我迭代list_of_num它打印每个数字时,我的想法是,现在这个每个数字将传递一个参数给devideBy2函数并返回结果num/2

但我结束了TypeError: 'int' object is not iterable

请帮助我了解我在哪里做错了。

谢谢你。

标签: pythonlist-comprehensiondecorator

解决方案


您需要调用您在函数内部传递的inner函数,而不是调用您正在装饰的函数。此外,您已经将传递的值转换为intin fnc,无需再次执行 ingetEven

def getEven(fnc): 
    def inner(list_of_val):

        # Call fnc here instead of devideBy2
        return [ fnc(value) for value in list_of_val ]
    return inner

@getEven
def devideBy2(num):
    return int(num)/2

list_of_num = [ 1, 2, 3, 4, 5]

print(devideBy2(list_of_num))

推荐阅读