在Python中进行子类化时仅命名的参数

时间:2014-01-15 14:22:37

标签: python inheritance

我想在子类的构造函数中添加一个可选的命名参数。如果未指定,则参数应与基础超类的参数相同。 E.g。

class Foo(object):
        def __init__(self, *args, **kwargs):
                print 'args', args
                print 'kwargs', kwargs


class Bar(Foo):
        # Here I want hello to be named-only, so that passing `hello` would be
        # optional, and all arguments would otherwise be passed to `Foo`.
        # However, such a syntax is incorrect
        #def __init__(self, *args, hello=False, **kwargs):
        #        Foo.__init__(self, *args, **kwargs)

        # I can do this instead. But this always requires passing `hello` as
        # the first argument
        def __init__(self, hello=False, *args, **kwargs):
                Foo.__init__(self, *args, **kwargs)


# Prints `args (2, 3)` and `kwargs {'for_foo': 4}`, but I want args to be
# `(1, 2, 3)` instead and 'hello` to be `False` instead of `1`
f = Bar(1, 2, 3, for_foo=4)

# This wouldn't work at all, since `hello` is passed twice. I want args
# to be printed as `(1, 2, 3)` again, and `hello` to be `True` and retained
# by `Bar.__init__`
f = Bar(1, 2, 3, hello=True)

这种情况是否存在模式?这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

class Bar(Foo):
    def __init__(self, *args, **kwargs):
        try:
            hello = kwargs.pop('hello')
        except KeyError:
            hello = False
        Foo.__init__(self, *args, **kwargs)

答案 1 :(得分:0)

尝试从kwargs获得“你好”。如果它在那里,删除它并将较小的kwargs传递给超类构造函数,否则只需调用超类构造函数:

#in Bar:
def __init__(self, *args, **kwargs):
    hello = None
    if "hello" in kwargs:
        hello = kwargs["hello"]
        del kwargs["hello"]
    Foo.__init__(self, *args, **kwargs)
    if not hello is None:
        do_something_with_hello(hello)