new-style-classes mixin

J.Jacob joost_jacob at hotmail.com
Fri Aug 9 14:05:41 CEST 2002


How about this one:

def doMixin(targetInstance, extraClass):
    class NewClass(targetInstance.__class__, extraClass): pass
    targetInstance.__class__ = NewClass

How come I did not think of this earlier!  Works for old style
classes.  Going to test it for new style classes when I am back home
tomorrow (they only have python versions 1.5.2 and 2.0 here).  I am
sure this needs some serious testing, for example what happens if you
add AC to an object of type CC?


------------------  file m2.py  --------------------------------
################################################################
# A couple of classic classes
#
class AC:
    def ma(self):
        print 'ac'

class BC:
    def mb(self):
        print 'bc'

class CC(AC):
    pass
#
################################################################
def doMixin(targetInstance, extraClass):
    class NewClass(targetInstance.__class__, extraClass): pass
    targetInstance.__class__ = NewClass


# Adding an old style class to an object of an old style class
cc1 = CC()
cc2 = CC()
print 'adding extraClass:%s to targetObj:%s of class:%s' % (BC,
        cc2, cc2.__class__)
doMixin(cc2, BC)
print 'cc1.__class__.__bases__:', cc1.__class__.__bases__
print 'cc2.__class__.__bases__:', cc2.__class__.__bases__
cc2.mb()
print hasattr(cc2, 'mb'), hasattr(cc1, 'mb')
------------------  file m2.py  --------------------------------

The output:

bash-2.04$ python m2.py
adding extraClass:__main__.BC to targetObj:<__main__.CC instance at
80db5e0> of class:__main__.CC
cc1.__class__.__bases__: (<class __main__.AC at 80db1f0>,)
cc2.__class__.__bases__: (<class __main__.CC at 80db688>, <class
__main__.BC at 80cfad8>)
bc
1 0



More information about the Python-list mailing list