Redo: Problem with dynamic creation of classes.

Steven W. Orr steveo at
Thu Aug 23 22:55:21 CEST 2007

Sorry, I had a small description problem. It's corrected below.

I have a base class B and a derived class D which inherits from B. I also
have a D2 class which inherits from D. D is used as a base class for most
of my generated classes. I have a "special" class which inherits from D2
because I need to override a couple of its methods. Anything based on D 
will inherit Encode and Decode from B.

class D(b.B):
      def __init__(self, data, timestamp = None):
          b.B.__init__(self, data)
          self.timestamp = timestamp

class D2( D ):
      def __init__(self, data, timestamp = None):
          DS.__init__(self, data, timestamp)
      def Decode(self):
      def Encode(self):

The generated classes come from this loop:

      for m in mdefs:
          mdef = mdefs[m]
          name = mdef['name'] + fbase
          if mdef.has_key('baseclass'):
              base_class_seq = mdef['baseclass']
              base_class_seq = DEFAULT_BASE_CLASS
          nclass = new.classobj( name, base_class_seq, globals() )

base_class_seq is either going to be (D,) or (D2,)

After I get through the class generation, I want to say
      globals()['IFRAMED2'].Decode = dynDecode
      globals()['IFRAMED2'].Encode = dynEncode
for the one class that inherited from D2. If I do that, I find that *all*
classes that call Encode or Decode are all calling dyn{En,De}code (which
is exactly what I *don't* want).

So I looked at the id values after class generation.

      print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode)
      print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode)
      print 'IFRAMED2 = ', IFRAMED2, id(IFRAMED2)
      print 'SNRMD = ', SNRMD, id(SNRMD)
      IFRAMED2.Decode = dynDecode
      IFRAMED2.Encode = dynEncode
      print 'IFRAMED2.Encode = ', IFRAMED2.Encode, id(IFRAMED2.Encode)
      print 'SNRMD.Encode = ', SNRMD.Encode, id(SNRMD.Encode)

Here's the output:

IFRAMED2.Encode =  <unbound method IFRAMED2.Encode> 1100623660
SNRMD.Encode =  <unbound method SNRMD.Encode> 1100623660
IFRAMED2 =  d.IFRAMED2 1076299644
SNRMD =  d.SNRMD 1103202364
IFRAMED2.Encode =  <unbound method IFRAMED2.dynEncode> 1100623660
SNRMD.Encode =  <unbound method SNRMD.dynEncode> 1100623660

So it looks like the IFRAMED2 class which inherits from D2 is starting out
with the same id value for Encode as SNRMD which inherits from D, even
though D2 defines its own Encode method.

Is it me of is it the interpreter doing something wrong?

Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at

More information about the Python-list mailing list