Preferred idion for adding instance methods

Discussion in 'Python' started by Dave Benjamin, Oct 14, 2003.

  1. 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 :
     
    Dave Benjamin, Oct 14, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Neo
    Replies:
    1
    Views:
    526
    Scott Allen
    Jan 7, 2005
  2. Bill Atkins
    Replies:
    3
    Views:
    144
    David Alan Black
    Apr 8, 2004
  3. Leon Bogaert
    Replies:
    19
    Views:
    331
    Robert Klemme
    Mar 23, 2008
  4. Raj Singh
    Replies:
    2
    Views:
    200
    Rick DeNatale
    May 29, 2008
  5. Kenneth McDonald
    Replies:
    5
    Views:
    326
    Kenneth McDonald
    Sep 26, 2008
Loading...

Share This Page