Вопрос

I have something like this:

MyClass(BaseClass):
    def __init__(self, *args, **kwargs):
        data = kwargs.pop('data', None)
        super(BaseClass, self).__init__(*args, **kwargs)

BaseClass is a representation of an API wrapper and it's init method receives a lot of arguments like, API_KEY, API_SECRET, OAUTH_TOKEN and OUATH_TOKEN_SECRET. My question is about what is the correct or cleanest way to create an instance of MyClass. I don't know if this would work:

if __name__ == '__main__':
    obj = MyClass(
        API_KEY,
        API_SECRET,
        OAUTH_TOKEN,
        OAUTH_TOKEN_SECRET,
        {'data': DATA}
    )

So, let's suppose that works, is it better to pack all the arguments in a dict and pass them to MyClass ?

Это было полезно?

Решение

**kwargs takes keyword arguments, not a dictionary:

obj = MyClass(
    API_KEY,
    API_SECRET,
    OAUTH_TOKEN,
    OAUTH_TOKEN_SECRET,
    data=DATA
)

Of course, you can use the **kwargs call convention to have your dictionary be applied as keyword arguments still:

obj = MyClass(
    API_KEY,
    API_SECRET,
    OAUTH_TOKEN,
    OAUTH_TOKEN_SECRET,
    **{'data': DATA}
)

Wether or not you pack the rest of the arguments into the keyword arguments depends entirely on the original method on BaseClass; does it accept those arguments as keyword arguments? In Python 3 that is not necessarily a given, nor do built-in (C defined) functions and methods always accept keyword arguments instead of positional arguments.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top