python - 使用函数装饰器从集合中删除一个值

标签 python wrapper decorator

有没有办法通过使用装饰器从集合中删除一个项目?我有一个函数可以生成一个数字的所有因子 - num,并返回一个集合。对于我正在处理的问题,我想返回不包括值-num 的集合。我想通过使用装饰器来实现,但不确定如何实现。

我在 euler.py 中的因子函数:

def factors(n):    
    return set(reduce(list.__add__, 
               ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

我要装饰的函数:

from euler import factors

def remove_last(func, *args, **kwargs):
    def wrapper(x):
         func.remove(x)
    return func

factors = remove_last(factors(10)) 
print factors

当前输出:

set([1, 10, 2, 5])

期望的输出:

set([1, 2, 5])

最佳答案

这是一个装饰器,它修改了一个返回集合的函数,这样返回的集合就没有函数参数:

def proper(func):
    def f(*args, **kwargs):
        s = func(*args, **kwargs)
        return s.difference(args)
    return f

例如:

@proper

def factors(n):    
    return set(reduce(list.__add__, 
               ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))

然后:

>>> factors(10)
{1, 2, 5}

我还没有用一个有多个参数的函数测试过它。

关于python - 使用函数装饰器从集合中删除一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36561277/

相关文章:

python - 无法从 python 3 中的输入文件中找到子字符串

C++:行为就像函数本身一样的函数包装器

c++ - 如何为结构体数组分配内存?

python - Flask:如果字段不存在,则 current_app AttributeError

python - pytorch "log_softmax_lastdim_kernel_impl"没有为 'torch.LongTensor' 实现

python - 逐列突出显示 Pandas 中每一行的差异

python - kwargs 覆盖 dict 子类

java - 如何知道何时在 RequestWrapper 对象中转发请求

oop - 带有保险杠贴纸的汽车是汽车的子类吗?

java - 装饰器模式(我可能滥用)的问题