adding instance methods after instantiation

Chris Gonnerman chris.gonnerman at newcenturycomputers.net
Sun Jun 24 00:11:04 EDT 2001


----- Original Message -----
From: "Bill Bell" <bill-bell at bill-bell.hamilton.on.ca>
> "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'.

Incorrect.  c1's current properties are ENTIRELY accessible within
c1.m2()...
see below for an explanation.

> 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'".

Of COURSE it does.  c1.a2 is NOT ASSIGNED until c1.m1() is called.
This code works fine:

######################################################
### 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 * self.a2

c1 = c()
c1.m2 = new.instancemethod(m2, c1, c)

### THIS gets the c1.a2 attribute set.  Remove it, and the next call fails.
c1.m1()

c1.m2()

print c1.a3







More information about the Python-list mailing list