-2

Possible Duplicate:
Understanding Python decorators

Just trying to "port" some Python code to Java, I came then across the following python code:

 @fake(lambda s, t, n: [(s.field(i+1), s) for i in range(n)])
 def split(secret, threshold, num_players):
     shares = []
     for i in range(1, num_players+1):
         # do some shares calculation
     return shares

There are quite some interesting constructs in this one that I never noticed before. Could anyone tell me what is the deal with this @fake thingy?

def fake(replacement):
    """Replace a function with a fake version."""
    def decorator(func):
        fakes = os.environ.get('FUNC_FAKE', '')
        if fakes == '*' or func.__name__ in fakes.split():
            return replacement
        else:
            return func
    return decorator

Further, does this lambda stand for a function name or what is the deal with that?

4

2 回答 2

5

首先,@fake是一个装饰者。

似乎要做@fake的是有条件地替换后面的函数,即splitlambda 函数(注意两者如何采用相同的参数)。

该决定基于FUNC_FAKE环境变量。如果后者等于*或包含split作为其标记之一,则进行替换。否则,它不是。

替换是lambda 函数这一事实并不重要。它可以很容易地变成一个正常的函数:

def split_replacement(s, t, n):
   return [(s.field(i+1), s) for i in range(n)])

@fake(split_replacement)
def split(s, t, n):
   ...

这整个结构相当莫名其妙。除了试图混淆其他程序员(或玩装饰器)之外,我很难找到以这种方式做事的理由。

于 2012-12-13T10:27:37.817 回答
4

第一个问题在别处得到解答。

对于你的第二个问题:

x = lambda a, b, *args, **kwargs: <expression>

只是一个简写

def x(a, b, *args, **kwargs):
    return <expression>

另请参见此处

于 2012-12-13T10:27:28.887 回答