Python: Inherit the superclass __init__

前端 未结 7 896
囚心锁ツ
囚心锁ツ 2020-12-01 02:51

I have a base class with a lot of __init__ arguments:

class BaseClass(object):
    def __init__(self, a, b, c, d, e, f, ...):
        self._a=a+         


        
相关标签:
7条回答
  • 2020-12-01 03:20

    You have to write it explicitly, but on the other hand, if you have lots of args, you should probably use *args for positional args and **kwargs for keyword args.

    class SubClass(BaseClass):
        def __init__(self, *args, **kwargs):
            super(SubClass, self).__init__(*args, **kwargs)
            # SubClass initialization code
    

    Another technique you could use is to minimize the code in init and then at the end of init function, call another custom function. Then in the subclass, you just need to override the custom function

    class BaseClass(object):
        def __init__(self, *args, **kwargs):
            # initialization code
            self._a = kwargs.get('a')
            ...
            # custom code for subclass to override
            self.load()
    
        def load():
            pass
    
    class SubClass(BaseClass)
        def load():
            # SubClass initialization code
            ...
    
    0 讨论(0)
提交回复
热议问题