Is there a way to specify a superclass at runtime?

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Oct 5 18:11:15 CEST 2009


Chris Colbert wrote:
> I dont think so, because that would require logic outside of the
> controller class to determine which controller to instantiate.
>
> My whole purpose for Controller is to encapsulate this logic.
>
> So, if the data should be simulated, then i just need to pass
> -simulate True as a command line argument, and the controller takes
> care of it...
>
> On Mon, Oct 5, 2009 at 3:44 PM, Richard Brodie <R.Brodie at rl.ac.uk> wrote:
>   
>> "Chris Colbert" <sccolbert at gmail.com> wrote in message
>> news:mailman.868.1254748945.2807.python-list at python.org...
>>
>>     
>>> I am trying to abstract this machinery in a single class called
>>> Controller which I want to inherit from either SimController or
>>> RealController based on whether a module level flag SIMULATION is set
>>> to True or False.
>>>       
>> At first sight, that seems kind of odd. Wouldn't it be simpler to have
>> SimController and RealController inherit from Controller?
>>
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>>     
Please don't top post.

Yet Richard's design is the way to go.

controller.py:

class Controller:
    def getInstance(simulation):
       if simulation:
          return SimController()
       else:
          return RealController()
    getInstance = staticmethod(getInstance)

class RealController(Controller):
    pass

class SimController(Controller):
    pass

myController = Controller.getInstance(simulation=True)


I personnally would define getInstance as a module function, but because 
you prefer to put all the logic in Controller... It doesn't really 
matter in the end.

Cheers,

Jean-Michel



More information about the Python-list mailing list