Is there a way to specify a superclass at runtime?

Chris Colbert sccolbert at gmail.com
Mon Oct 5 09:49:31 EDT 2009


because when i import this module, the classes will already be
determined by the intitial flag setting.

i.e.
SIMULATION = False

class SimController(object):
   def foo(self):
       print 'bar'

class RealController(object):
   def foo(self):
       print 'baz'

if SIMULATION:
   SuperKlass = SimController
else:
   SuperKlass = RealController

class Controller(SuperKlass):
   pass





In [2]: import testcontroller

In [3]: testcontroller.SIMULATION
Out[3]: False

In [4]: c = testcontroller.Controller()

In [5]: c.foo()
baz

In [6]: testcontroller.SIMULATION = True

In [7]: c = testcontroller.Controller()

In [8]: c.foo()
baz

On Mon, Oct 5, 2009 at 3:32 PM, MRAB <python at mrabarnett.plus.com> wrote:
> Chris Colbert wrote:
>>
>> I have an application that needs to run different depending on whether
>> the input data is being simulated, or provided from instrumentation.
>>
>> 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.
>>
>> so I have something like this:
>>
>>
>> SIMULATION = False
>>
>> class SimController(object):
>>    "do sim stuff here"
>>
>> class RealController(object):
>>    " do real stuff here"
>>
>> class Controller(SuperKlass):
>>    pass
>>
>>
>> so if SIMULATION == False I want to be able to instance a Controller
>> object that inherits from RealController and vice-versa.
>>
>> I thought this might be possible with metaclasses, but I didnt find
>> anything useful in the docs or on google.
>>
>> Thanks for any help!
>>
> Why not just:
>
> SIMULATION = False
>
> class SimController(object):
>    "do sim stuff here"
>
> class RealController(object):
>    " do real stuff here"
>
> if SIMULATION:
>    SuperKlass = SimController
> else:
>    SuperKlass = RealController
>
> class Controller(SuperKlass):
>    pass
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list