8
\$\begingroup\$

I have a superclass with several subclasses. Each subclass overrides the "solve" method with some a different algorithm for estimating the solution to a particular problem. I'd like to efficiently create an instance of each subclass, store those instances in a list, and then take the sum (or average) of the estimates that the subclasses give:

class Technique():
 def __init__(self):
 self.weight = 1
 def solve(self, problem):
 pass
class Technique1(Technique):
 def __init__(self):
 super()
 def solve(self,problem):
 return 1
class Technique2(Technique):
 def __init__(self):
 super()
 def solve(self,problem):
 return 6
 class Technique3(Technique):
 def __init__(self):
 super()
 def solve(self,problem):
 return -13
testCase = 3
myTechniques = []
t1 = Technique1()
myTechniques.append(t1)
t2 = Technique1()
myTechniques.append(t2)
t3 = Technique1()
myTechniques.append(t3)
print(sum([t.solve(testCase) for t in myTechniques])

The code at the end feels very clunky, particularly as the number of subclasses increases. Is there a way to more efficiently create all of the instances?

asked Jul 13, 2015 at 23:19
\$\endgroup\$

1 Answer 1

12
\$\begingroup\$

You might try this:

myTechniques = [cls() for cls in Technique.__subclasses__()]

Note that it does not return indirect subclasses, only immediate ones. You might also consider what happens if some subclass of Technique is itself abstract. Speaking of which, you should be using ABCMeta and abstractmethod.

answered Jul 13, 2015 at 23:32
\$\endgroup\$
2
  • \$\begingroup\$ That's exactly what I was looking for. Thanks! \$\endgroup\$ Commented Jul 13, 2015 at 23:55
  • \$\begingroup\$ If this question were asked again today, I'd suggest __init_subclass__ as the cleanest answer. \$\endgroup\$ Commented Dec 30, 2017 at 4:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.