Is there a way to specify a superclass at runtime?
Chris Colbert
sccolbert at gmail.com
Mon Oct 5 11:33:01 EDT 2009
that's a good idea.
Thanks!
On Mon, Oct 5, 2009 at 4:18 PM, MRAB <python at mrabarnett.plus.com> wrote:
> Chris Colbert wrote:
>>
>> 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
>>
> [snip]
> You could put the Controller class inside a factory function:
>
> def Controller():
> if SIMULATION:
> SuperKlass = SimController
> else:
> SuperKlass = RealController
> class Controller(SuperKlass):
> pass
> return Controller()
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list