0

我正在使用Python 2编写一个工具,然后单击它在硬件中读取/写入寄存器。我有两个接受完全相同选项的函数。不同之处在于它们处理输入并将输出直接输出到不同的设备。

这是我到目前为止所拥有的:

@cli.command()
@click.option('--r0', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r1', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r2', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
def mydevice1(r0, r1, r2):
    # Handle inputs for device 1
    click.echo('myfunc1')

@cli.command()   
@click.option('--r0', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r1', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r2', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
def mydevice2(r0, r1, r2):
    # Handle inputs for device 2
    click.echo('myfunc2')

这两个函数将以相同的方式处理输入,唯一的区别是它们会将处理的信息传递给不同的设备。换句话说,我想要的是

@click.option('--r0', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r1', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
@click.option('--r2', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
def handle_common_options(r0, r1, r2):
    # Handle common options
    pass

@cli.command()
def mydevice1():
    handle_common_options()
    # pass processed options to device 1

@cli.command()
def mydevice2():
    handle_common_options()
    # pass processed options to device 2

这可能吗?

4

1 回答 1

2

当然。

@decorator
def f():
    pass

方法

def f():
    pass
f = decorator(f)

所以:

decorator0 = cli.command()
decorator1 = click.option('--r0', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
decorator2 = click.option('--r1', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)
decorator3 = click.option('--r2', type=click.IntRange(-2, 0xffffffff, clamp=False), default=-2)

common_decorator = lambda f: decorator0(decorator1(decorator2(decorator3(f))))

@common_decorator
def mydevice1(r0, r1, r2):
    click.echo('myfunc1')

@common_decorator
def mydevice2(r0, r1, r2):
    click.echo('myfunc2')

没有 lambda:

def common_decorator(f):
    return decorator0(decorator1(decorator2(decorator3(f))))
于 2016-11-23T02:20:27.570 回答