Preferred idion for adding instance methods

D

Dave Benjamin

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top