How to replace a method in an instance.

James Stroud jstroud at mbi.ucla.edu
Fri Aug 24 13:58:28 EDT 2007


Steven W. Orr wrote:
> Ok. I have a collection of classes that are produced by a factory.  They
> all inherit from a baseclass. One (maybe more) of the classes inherits a  
> method that he shouldn't. All I want is to be able to change that
> particular class so that he will have the special method that he needs    
> instead of the default one that he inherits. I was thinking that instead 
> of making a special class for CC to inherit from which would give him his 
> special replacement method(s), I could simply assign them in a manner 
> which would more easily lend itself to later being table driven.
> 
> If I had a choice, I'd rather not do it in init. Instead, I'd rather be 
> able to say something like 
> CC.m1 = repmeth
> but since in the real world, CC inherits from his baseclass, the above 
> assignment causes the baseclass to be altered. :-(
> 
> Please tell me if I need to provide more.


def f1(self):
   print 'f1'

def f2(self):
   print 'f2'

def classfactory(replacements=None):
   class _C(object):
     def doit(self):
       print 'doit'
     def doit2(self):
       print 'doit2'
   if replacements is not None:
     for fname, f in replacements.items():
       setattr(_C, fname, f)
   return _C

Aclass = classfactory()
Aclass().doit()

Aclass2 = classfactory({'doit':f1, 'doit2':f2})
Aclass().doit2()
Aclass2().doit2()



Here's the output:


py> def f1(self):
...   print 'f1'
...
py> def f2(self):
...   print 'f2'
...
py> def classfactory(replacements=None):
...   class _C(object):
...     def doit(self):
...       print 'doit'
...     def doit2(self):
...       print 'doit2'
...   if replacements is not None:
...     for fname, f in replacements.items():
...       setattr(_C, fname, f)
...   return _C
...
py> Aclass = classfactory()
py> Aclass().doit()
doit
py>
py> Aclass2 = classfactory({'doit':f1, 'doit2':f2})
py> Aclass().doit2()
doit2
py> Aclass2().doit2()
f2


James



More information about the Python-list mailing list