2014-01-15 3 views
0

서브 클래스의 생성자에 선택적으로 명명 된 인수를 추가하려고합니다. 지정되지 않은 경우 인수는 기본 수퍼 클래스의 인수와 동일해야합니다. 예 :파이썬에서 서브 클래스화할 때 명명 된 전용 인수

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) 

그런 경우 패턴이 있습니까? 이 일을하는 올바른 방법은 무엇입니까?

답변

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

을 ... 또는 하나의 예외 처리를 사용하지 않는 링크 된 질문에서 유사한 솔루션을 사용할 수 있습니다 (따라서 더 빠를 수 있음) – dragonroot

0

kwargs에서 "hello"를 사용해보십시오. 이있을 경우,이를 제거하고 생성자를 슈퍼 클래스에 작은 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) 
관련 문제