Inheritance best practice : *args, **kwargs or explicitly specifying parameters

后端 未结 6 1641
长发绾君心
长发绾君心 2020-12-23 02:10

I often find myself overwriting methods of a parent class, and can never decide if I should explicitly list given parameters or just use a blanket *args, **kwargs

6条回答
  •  一个人的身影
    2020-12-23 02:45

    If you are certain that Child will keep the signature, surely the explicit approach is preferable, but when Child will change the signature I personally prefer to use both approaches:

    class Parent(object):
        def do_stuff(self, a, b):
            # some logic
    
    class Child(Parent):
        def do_stuff(self, c, *args, **kwargs):
            super(Child, self).do_stuff(*args, **kwargs)
            # some logic with c
    

    This way, changes in the signature are quite readable in Child, while the original signature is quite readable in Parent.

    In my opinion this is also the better way when you have multiple inheritance, because calling super a few times is quite disgusting when you don't have args and kwargs.

    For what it's worth, this is also the preferred way in quite a few Python libs and frameworks (Django, Tornado, Requests, Markdown, to name a few). Although one should not base his choices on such things, I'm merely implying that this approach is quite widespread.

提交回复
热议问题