adding instance methods after instantiation

Bill Bell bill-bell at bill-bell.hamilton.on.ca
Sat Jun 23 16:23:38 EDT 2001


"Chris Gonnerman" 
<chris.gonnerman at newcenturycomputers.net> wrote, in part:
> From: "Skip Montanaro" <skip at pobox.com>
> >     Lee> Is there some way to make m2 an instance method so that it
> >     will Lee> automatically get passed c1 as its first argument?
> > 
> > Check out the instancemethod function of the new module.
> 
> Here is code based on Lee's sample:
> 
> ######################################################
> ### adding an instance method after the fact
> import new
> 
> class c:
>   def __init__(self):
>     self.a1 = 1
>   def m1(self):
>     self.a2 = 2
> 
> def m2(self): #note, outside of class c definition
>   self.a3 = 3
> 
> c1 = c()
> c1.m2 = new.instancemethod(m2, c1, c)
> 
> c1.m2()
> print c1.a3

Although 'a3' may appear to act as a method of instance 'c1' 
unfortunately not all of the properties of 'c1' are available within 'm2'.

For instance, if the definition of 'm2' is replaced with 

def m2(self):
  self.a3 = 3 * self.a2

the Python interpreter complains that, "AttributeError: c instance 
has no attribute 'a2'".




More information about the Python-list mailing list