Need a better understanding on how MRO works?

Steven W. Orr steveo at syslang.net
Sat Aug 25 18:02:20 EDT 2007


Given the following code: (I hope it's as simple as possible) :-)
#! /usr/bin/python
import new
class BASE:
     def __init__( self ):
         print 'Hello from BASE init'
     def m1( self ):
         print 'M1 Base: Self = ', self

def m1replace( self ):
     print 'm1replace:Self = ', self

class D1(BASE):
     def __init__(self):
         BASE.__init__(self)

def __InitDS101Classes():
     name = 'C1'
     nclass = new.classobj(name,(D1,),globals())
     globals()[name] = nclass
     name = 'C2'
     nclass = new.classobj(name,(D1,),globals())
     globals()[name] = nclass
     globals()[name].m1 = m1replace

__InitDS101Classes()

s = C1()
s.m1()
t = C2()
t.m1()

I get the following output:

1100 > ./foo1.py
Hello from BASE init
m1replace:Self =  <__main__.C1 instance at 0xb7e637cc>
Hello from BASE init
m1replace:Self =  <__main__.C2 instance at 0xb7e6388c>

But if I make BASE inherit from object
class BASE(object):
then I get this:

1100 > ./foo1.py
Hello from BASE init
m1replace:Self =  <__main__.NewClass instance at 0xb7f5070c>
Hello from BASE init
M1 Base: Self =  <__main__.D1 instance at 0xb7f5088c>

Can someone please explain why the assignment to C2.m1 would overwrite
BASE.m1?

TIA

-- 
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 syslang.net



More information about the Python-list mailing list