Home > Software engineering >  Overwrite a function depending on given parameters, during initializing Child class #Python
Overwrite a function depending on given parameters, during initializing Child class #Python

Time:08-17

It's a minimum example of python inheritance:

class Parent(object):
     def __init__(self, time):
         self.time=time
     def forward(self):
         return 0
 
class Child(Parent):
     def forward(self):
         return 1

I want to overwrite the forward function based on self.time when initializing Child class.

I.e. if self.time==2, use Parent's forward function instead of Child's.

class Child(Parent):
     def __init__(self, time):
         super(Child, self).__init__(time)
         if self.time==2:
             pass
             #todo: use super().forward instead
     def forward(self):
         return 1

Can I achieve it in python (3.8 )?

CodePudding user response:

Methods can be assigned dynamically in Python:

class Child(Parent):
    def __init__(self, time):
        super(Child, self).__init__(time)
        if self.time == 2:
            self.forward = super(Child, self).forward

    def forward(self):
        return 1

Or you can call Parent.forward in Child.forward:

class Child(Parent):
    def forward(self):
        return super(Child, self).forward() if self.time == 2 else 1
  • Related