dynamic inheritance

bruno at modulix onurb at xiludom.gro
Fri Jun 9 10:11:37 CEST 2006


alf wrote:
> is there any way to tell the class the base class during runtime?
> 
Technically, yes - the solution depending on your definition of "during
runtime"

FWIW, the class statement is evaled at import/load time, which is
"during runtime".... So if you want to use one or other (compatible)
classes depending on configuration or system or like, you can use a
conditionnal at the top level, *before* the class statement is eval'd. ie:

import os
if os.name == 'posix':
  import posixmodule as basemodule
elif os.name == 'nt':
  import ntmodule as basemodule
# etc...

class MyClass(basemodule.baseclass):
  # class def here


If you want to dynamically change the base class (or one of the base
classes) during execution (ie: after the class statement has been
eval'd), read Kay Schluehr's answer.

*But* you'd probably better tell us about the problem you're trying to
solve. Since in Python, inheritance is mostly about implementation (ie:
 not needed for subtyping), your problem would probably be best solved
with composition/delegation, for which Python offers a good support:

class MyClass(object):
   def __init__(self, delegate):
       self._delegate = delegate

  def __getattr__(self, name):
       return getattr(self._delegate, name)

or, if you don't want to explicitely pass the delegate at instanciation
time:

import os
if os.name == 'posix':
  import posixmodule as basemodule
elif os.name == 'nt':
  import ntmodule as basemodule
# etc...

class MyClass(object):
    _delegate_class = basemodule.SomeClass

    def __init__(self):
        self._delegate = self._delegate_class()

# etc

there are of course some variants of the above solutions, but one can't
tell you which one to use without knowing more about your actual problem.

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list