Is there a way to specify a superclass at runtime?

MRAB python at mrabarnett.plus.com
Mon Oct 5 16:18:35 CEST 2009


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()



More information about the Python-list mailing list