In various situations, we need a mechanism to Initialize all Sub classes for a given Super class. For instance, let’s assume that we have a Super class called ArithmeticOperation and another 4 classes derived from it (Addition, Subtraction, Multiplication and Division).

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
class ArithmeticOperation(object): def __init__(self, x, y): self.x = x self.y = y def compute(self): # overload this method to compute pass pass class Addition(ArithmeticOperation): def compute(self): result = self.x + self.y print "Addition : {}".format(result) pass pass class Subtraction(ArithmeticOperation): def compute(self): result = self.x - self.y print "Subtraction : {}".format(result) pass pass class Multiplication(ArithmeticOperation): def compute(self): result = self.x * self.y print "Multiplication : {}".format(result) pass pass class Division(ArithmeticOperation): def compute(self): result = float(self.x) / float(self.y) print "Division : {}".format(result) pass pass |

One way of doing it is Initializing each Sub class separately.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
if __name__ == '__main__': num_1 = 20 num_2 = 10 a = Addition(num_1, num_2) a.compute() s = Subtraction(num_1, num_2) s.compute() m = Multiplication(num_1, num_2) m.compute() d = Division(num_1, num_2) d.compute() |

But if there are hundreds of Sub classes, we need to think of another mechanism.Â That’s where .__subclasses__() becomes very useful. We can use that method to Iterate and Initialize all Sub classes for that given Super Class. You can do it like this,

1 2 3 4 5 6 7 8 |
if __name__ == '__main__': num_1 = 20 num_2 = 10 for Operation in ArithmeticOperation.__subclasses__(): factor = Operation(num_1, num_2) factor.compute() pass |

Hope this post helped someone who’s looking for a way to Iterate and Initialize all Sub classes for a given Super Class using python. đź™‚