KubiK888
KubiK888

Reputation: 4723

How to slightly modify an inherited attribute from parent __init__() with minimal changes in the child class in Python?

The code as below:

def some_function1():
    pass

def some_function2():
    pass

def some_function3():
    pass

def some_function4():
    pass

class ReporterClass():
    def __init__(self, data_reporter):
        self.data_reporter = data_reporter

class ParentClass():
    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2
        self.datacollector = ReporterClass(data_reporter={
            'Report info 1': some_function1,
            'Report info 2': some_function2,
            'Report info 3': some_function3,
            })

class ChildClass(ParentClass):
    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2
        self.datacollector = ReporterClass(data_reporter={
            'Report info 1': some_function1,
            'Report info 2': some_function2,
            'Report info 3': some_function3,
            'Report info 4': some_function4,
            })

This works fine in this toy example, but the problem I have in the actual code is that there are many parameters in the __init__(), for example, param1... param100. Similarly, there are many dictionary items within data_reporter, for example, Report info 1 ... Report info 100. I like to simply modify by adding 'Report info 4': some_function4 to the self.datacollector in the ChildClass without having to completely overwrite the parent's __init__() and having to repeat all the parameter code. Any tips or suggestions will be appreciated.

--- Edits ---

To explain more in detail. Based on the suggestions, I would create the child class as ChildClass1. However, my class has many parameters in the initialization. Not only I need to write them all in child class' __init__(), I also need to "repeat" them in the super().__init__(). So I am wondering if there is a more convenient and elegant way to not have to repeat themselves. Something like the ChildClass2?

class ChildClass1(ParentClass):
    def __init__(self, 
                        param1, 
                        param2,
                        ., # Very long list of parameters
                        .,
                        .,
                        param100,
    ):
        super().__init__(
                        param1, 
                        param2,
                        ., # Very long list of parameters
                        .,
                        .,
                        param100
                        )
        self.datacollector.data_reporter['Report info 4'] = some_function4

class ChildClass2(ParentClass):
    def __init__(self, *args):
        some_var_to_store_parent_init_params = super().__init__.attr

        for param in some_var_to_store_parent_init_params:
            # somehow assign it back to ChildClass' args

        super().__init__(some_var_to_store_parent_init_params)

        self.datacollector.data_reporter['Report info 4'] = some_function4

Upvotes: 1

Views: 69

Answers (2)

Reblochon Masque
Reblochon Masque

Reputation: 36652

Calling super()__init__() will help you make good reuse of the parent __init__; then you can add the necessary additional functions in the 'ReporterClass.datacollector' attribute of the ChildClass

You could further refactor the way ReporterClass.datacollector is build to populate it with parameters - instead, here, additional values are directly added after the call to super().

def some_function1(): pass    
def some_function2(): pass
def some_function3(): pass
def some_function4(): pass


class ReporterClass:
    def __init__(self, data_reporter):
        self.data_reporter = data_reporter


class ParentClass:
    def __init__(self, param1, param2):
        self.param1 = param1
        self.param2 = param2
        self._data_reporter = {'Report info 1': some_function1,
                               'Report info 2': some_function2,
                               'Report info 3': some_function3}
        self.datacollector = ReporterClass(self._data_reporter)


class ChildClass(ParentClass):
    def __init__(self, param1, param2):
        super().__init__(param1, param2)
        self.datacollector.data_reporter['Report info 4'] = some_function4


if __name__ == '__main__':

    print(ParentClass(1, 2).datacollector.data_reporter)
    print(ChildClass(3, 4).datacollector.data_reporter)

[edit] -----------

You can use args, kwargs if you are finding the handling of many parameters cumbersome, like this:

class ParentClass:
    def __init__(self, *args):
        self.param1, self.param2 = args
        self._data_reporter = {'Report info 1': some_function1,
                               'Report info 2': some_function2,
                               'Report info 3': some_function3}
        self.datacollector = ReporterClass(self._data_reporter)


class ChildClass(ParentClass):
    def __init__(self, *args):
        super().__init__(*args)
        self.datacollector.data_reporter['Report info 4'] = some_function4


if __name__ == '__main__':

    print(ParentClass(1, 2).datacollector.data_reporter)
    print(ChildClass(3, 4).datacollector.data_reporter)

Upvotes: 1

Daniel Walker
Daniel Walker

Reputation: 6740

Assuming I understand your question correctly, would the following do what you're looking for?

class MaybeWorks:
    def __init__(self, num_funcs, *args):
        for k, arg in enumerate(args):
            setattr(self, 'param'+str(k+1), arg)
        data_reporter=dict()
        for k in range(num_funcs):
            data_reporter['Report info '+str(k+1)] = globals()['some_function'+str(k+1)]
        self.datacollector = ReporterClass(data_reporter)

Upvotes: 0

Related Questions