How to pass all arguments from __init__ to super class

前端 未结 1 1597
情书的邮戳
情书的邮戳 2021-02-07 14:19

IS there any magic I can use in Python to to effectively use super constructor by just adding some extra arguments?

Ideally I\'d like to use something like:



        
相关标签:
1条回答
  • 2021-02-07 15:01

    You are almost there:

    class ZipArchive(zipfile.ZipFile):
        def __init__(self, *args, **kwargs):
            """
            Constructor with some extra params:
    
            * verbose: be verbose about what we do. Defaults to True.
    
            For other params see: zipfile.ZipFile
            """
            self.verbose = kwargs.pop('verbose', True)
    
            # zipfile.ZipFile is an old-style class, cannot use super() here:
            zipfile.ZipFile.__init__(self, *args, **kwargs)
    

    Python 2 is a little persnickety and funny about mixing *args, **kwargs and additional named keyword arguments; your best bet is to not add additional explicit keyword arguments and just take them from kwargs instead.

    The dict.pop() method removes the key from the dictionary, if present, returning the associated value, or the default we specified if missing. This means that we do not pass verbose on to the super class. Use kwargs.get('verbose', True) if you just want to check if the paramater has been set without removing it.

    0 讨论(0)
提交回复
热议问题