I have spent the day trying to find an answer to this question but have come up with nothing.
Suppose I have several classes, each containing a methods that are identical to those in the others.
class A:
def __init__(self, attr1, attr2, color):
self.__attr1 = attr1
self.__attr2 = attr2
self.__color = color
def set_color(self, color):
self.__color = color
class B:
def __init__(name, attr3, attr4, color):
self.__attr3 = attr3
self.__attr4 = attr4
self.__color = color
def set_color(self, color):
self.__color = color
In this example, the identical methods are reduced to just one identical method, set_color, to illustrate what I am trying to do.
Is there a way to eliminate repeating code, perhaps with an abstract class as follows?
class Parent:
def set_color(self, color):
self.__color = color
class A(Parent):
def __init__(self, attr1, attr2, color):
self.__attr1 = attr1
self.__attr2 = attr2
self.__color = color
class B(Parent):
def __init__(name, attr3, attr4, color):
self.__attr3 = attr3
self.__attr4 = attr4
self.__color = color
exampleA = A(attr1, attr2, "blue)
I want to be able change from blue to red in a way like this
so that I don't have to define the same methods within each class A
and B
exampleA.set_color("red")
but this doesn't work as I expected it to, it doesn't change the value of exampleA.__color