Preferred idion for adding instance methods

Dave Benjamin ramen at lackingtalent.com
Tue Oct 14 12:59:29 EDT 2003


I just noticed that the "new" module is deprecated in Python 2.3. Since the
old way of adding a method to a particular instance (not its class) was to
use new.instancemethod, I am guessing that we are now supposed to use
types.MethodType. Is this the preferred idiom for adding an instance method?

import new
import types

class Test(object):
    def __init__(self, x):
        self.x = x
            
t = Test(42)
            
def print_x(self):
    print self.x
                
# The old way.
#t.print_x = new.instancemethod(print_x, t, Test)

# The new way?
t.print_x = types.MethodType(print_x, t, Test)
                
t.print_x()

Thanks,
Dave

-- 
.:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g   l i f e   o u t   o f   t h e   c o n t a i n e r :




More information about the Python-list mailing list