A (unpythonic) pythonable mixin recipe.

Paolino paolo_veronelli at tiscali.it
Tue Aug 16 10:38:47 EDT 2005


I had always been negative on the boldeness of python on insisting that 
unbound methods should have been applied only to its im_class instances.
Anyway this time I mixed in rightly, so I post this for comments.

###### looking for a discovery .Start #################

class _Mixin(object):
   def __init__(self,main,instance,*args,**kwargs):
      # do mixin businnes
      main.__reinit__(self,instance) # the caveated interface
      # probably missing __reinit__ in main
      # one could assume main.__init__ should do
   def mixinMethod(self):
     print 'mixinMethod on',repr(self)

def Mixin(instance,*args,**kwargs):
   klass=instance.__class__
   return type('Mix+%s'%klass.__name__,(_Mixin,klass),{})(klass,instance)

############ end of hot water discovery ##########

class Base(object):
   def __reinit__(self,another):
     # do something so that self is like another (painful in general)
     # easy for mutables, impossible for other
     pass

b=Base()
b=Mixin(b)

assert isinstance(b,Base)
b.mixinMethod() # doesn't fail with absurds

#### The next doesn't work ####
# l=[1,2,3]
# l.__reinit__=l.__init__  # exception IMAConservativeLanguage

class L(list):
   __reinit__=lambda self,other:list.__init__(self,other)

l=L([1,2,3])
l=Mixin(l)
l.mixinMethod()

Regards Paolino



	

	
		
___________________________________ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it



More information about the Python-list mailing list