1
class BaseCls:
    def foo(self):
        print("BaseCls")

class ChildClsA(BaseCls):
    def foo(self):
        print("ChildClsA")

class ClildClsB(BaseCls):
    def foo(self):
        print("ChildClsB")



inputStr=raw_input("press A or B\n")

if(inputStr=="A"):
    obj=ChildClsA()
if(inputStr=="B"):
    obj=ClildClsB()

obj.foo()

'if' statement can deal with this situation. However, how to decide creating a child class without using 'if' statement When I have more than one hundred children of BaseCls,

4 Answers4

2

You can store your classes in a dictionary:

classes = dict(A=ChildClsA, B=ChildClsB)

obj = classes[inputStr]()
flornquake
  • 3,156
  • 1
  • 21
  • 32
0

I'd double check your design, but a simplistic way would be to create a lookup of the valid subclasses from your base:

import re
lookup = {re.search('([A-Z][A-Za-z_]*$)', cls.__name__).group(1): cls for cls in BaseCls.__subclasses__()}
# {'A': <class '__main__.ChildClsA'>, 'B': <class '__main__.ClildClsB'>}

input_str = raw_input('Please enter one of {}:'.format(', '.join(lookup)))
new_class = lookup[input_str]()

Note: use whatever criteria makes sense to extract the name for lookup purposes

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • Ok, this is not be most "simplistic" way, but +1 because this kicks ass and pretty Pythonic. –  Aug 21 '13 at 10:11
0

Another way would be to pack the user input into a string an execute that.

input_ = raw_input( "Please enter the class name:" )
try:
    exec( "%s().foo()" % input_ )
except NameError:
    print "Invalid class name entered"

I know that exec is evil :-)

So also take a look at why-should-exec-and-eval-be-avoided

Community
  • 1
  • 1
Robert Caspary
  • 1,584
  • 9
  • 7
0

This is a perfect case for a factory pattern.

Create your child classes independently en register them with the factory. Then use what key you have to call the factory and have it instantiate the desired class for you.

The simplest factory is a dictionary but you can also build a nice factory class with additional features.

Ber
  • 40,356
  • 16
  • 72
  • 88