我可以使用对象的单击命令,使用继承来删除重复代码吗?

Can I have click commands for objects, using inheritance to de-duplicate code?

如果你看看我的 lidtk repository, especially the classifiers, you can see that the following files are almost identical (current version 以防将来修复):

他们都继承自lidtk.LIDClassifier并且他们都有命令

Usage: lidtk <<module name>> [OPTIONS] COMMAND [ARGS]...

  Use the <<module name>> language classifier.

Options:
  --help  Show this message and exit.

Commands:
  get_languages
  predict          
  print_languages
  wili             
  wili_k           
  wili_unk         

是否可以删除重复的点击代码?我想使用继承来去重代码。

扫了一眼你的回购协议,我想你想要的是这样的:

import click

def group_factory(group, name, params):
    """This creates a subcommand 'name' under the existing click command
    group 'group' (which can be the main group), with sub-sub-commands
    'cmd1' and 'cmd2'. 'params' could be something to set the context
    for this group.
    """

    @group.group(name=name)
    def entry_point():
        pass

    @entry_point.command()
    @click.option("--foo")
    def cmd1(foo):
        print("CMD1", name, params, foo)

    @entry_point.command()
    @click.option("--bar")
    def cmd2(bar):
        print("CMD2", name, params, bar)

    return entry_point

您可以使用 group_factory 的 return 值作为一组不同脚本中的主要入口点:

if __name__ == "__main__":
    ep = group_factory(click, "", "something")
    ep()

... 或者您可以使用 group_factory 在一些顶级命令下以不同的名称重复构建相同的子命令层次结构(并且具有不同的 params):

@click.group()
def cli():
    pass

group_factory(cli, "a", 1)
group_factory(cli, "b", 2)
group_factory(cli, "c", 3)