Reputation: 7353
I have a class KA
, which has two methods, add()
and subtract()
, and an abstract child class KAX
. KAX
has an abstract method, multiply()
. There is another class KB
which inherits KA
, and by extension has access to KAX.multiply()
. I would like to overwrite/define KAX.multiply()
from class KB
. How to do this?
So far what I could think of is define a private method __multiply()
under class KB
, and then redefine under KB.__init__()
as follows:
self.KAX.multiply = self.__multiply()
This works. However, I am wondering if there is a better way to do what I am trying to achieve here. Thank you.
My current code:
from abc import ABC, abstractmethod
class KA():
def __init__(self):
self.A = 3
self.B = 10
self.C = self.B**self.A
@abstractmethod
def add(self): pass
@abstractmethod
def subtract(self): pass
class KAX(ABC):
@abstractmethod
def multiply(self): pass
class KB(KA):
def __init__(self, A = 3, B = 10):
#super(KB, self).__init__()
self.A = A
self.B = B
self.KAX.multiply = self.__multiply
self.KAX.multiply()
self.C = self.KAX.multiplication
def add(self):
self.addition = self.A + self.B
def subtract(self):
self.subtraction = self.A - self.B
def __multiply(self):
self.KAX.multiplication = self.A*self.B
if __name__ == '__main__':
kb = KB(A = 4, B = 2)
# check values of variables: A, B, C
print('Parameters: A, B, C')
print(''.join(['kb.{}: {}\n'.format(vname, getattr(kb,vname)) for vname in ['A', 'B', 'C']]))
# apply methods
kb.add()
kb.subtract()
kb.KAX.multiply()
# show results
result_string = 'Result: \n\t addition: {}\t | subtraction: {}\t | multiplication: {}'
print(result_string.format(kb.addition, kb.subtraction, kb.KAX.multiplication))
The output of this code results in:
Parameters: A, B, C
kb.A: 4
kb.B: 2
kb.C: 1000
Result:
addition: 6 | subtraction: 2 | multiplication: 8
Upvotes: 0
Views: 395
Reputation: 11
Maybe you could try making a new class called KB.KAX that extends KA.KAX and then implementing your method like so:
class KA():
class KAX():
@abstractmethod
def multiply(self): pass
class KB(KA):
class KAX(KA.KAX):
def multiply(self):
print("doing stuff")
Upvotes: 1
Reputation: 44858
KAX
isn't a child class, it's just a class defined within another class. So, you can subclass it and override its methods:
class KB(KA):
class KAX(KA.KAX):
def multiply(self):
print("hello!")
Upvotes: 1