小编ejm*_*ejm的帖子

在python中子类化和覆盖生成器函数

我需要覆盖父类的方法,它是一个生成器,我想知道正确的方法来做到这一点.以下是否有任何问题,或更有效的方法?

class A:
    def gen(self):
        yield 1
        yield 2

class B(A):
    def gen(self):
        yield 3
        for n in super().gen():
            yield n
Run Code Online (Sandbox Code Playgroud)

python python-3.x

15
推荐指数
2
解决办法
3944
查看次数

在Python中以前缀表示法处理命令行参数

我正在尝试解析Python中的命令行,如下所示:

$ ./command -o option1 arg1 -o option2 arg2 arg3
Run Code Online (Sandbox Code Playgroud)

换句话说,该命令采用无限数量的参数,并且每个参数可以可选地在前面加上一个-o选项,该选项与该参数具体相关.我认为这被称为"前缀表示法".

在Bourne shell中,我会做类似以下的事情:

while test -n "$1"
do
    if test "$1" = '-o'
    then
        option="$2"
        shift 2
    fi
    # Work with $1 (the argument) and $option (the option)
    # ...
    shift
done
Run Code Online (Sandbox Code Playgroud)

看看Bash教程等,这似乎是公认的习惯用法,所以我猜测Bash已经过优化,可以通过这种方式使用命令行参数.

试图在Python中实现这种模式,我的第一个猜测是使用pop(),因为这基本上是一个堆栈操作.但我猜这在Python上不会有效,因为参数列表的sys.argv顺序错误,必须像队列一样处理(即从左侧弹出).我已经读过,列表没有优化用作Python中的队列.

所以,我的想法是:转换argvcollections.deque和使用popleft(),反向argv使用reverse()和使用pop(),或者只是使用int列表索引本身.

有没有人知道更好的方法来做到这一点,否则我的哪些想法将是最好的Python实践?

python stack prefix command-line-arguments data-structures

7
推荐指数
3
解决办法
5996
查看次数