mapping a string to an instancemethod

M

mh

The following bit of code will allow an instance member to
be called by reference. How can I map a string (e.g.
"hello1" or "Foo.hello1" to a the instance member?

class Foo:
def hello1(self, p):
print 'hello1', p
def hello2(self, p):
print 'hello2', p
def dispatch(self, func, p):
func(self,p)

f=Foo()
f.dispatch(Foo.hello1, 23)
f.dispatch(Foo.hello1, 24)

f.dispatch_as_string("hello1", 23) ## this is what I want to do.

Many TIA and apologies if this is a FAQ, I googled and couldn't
find the answer.
 
A

attn.steven.kuo

The following bit of code will allow an instance member to
be called by reference. How can I map a string (e.g.
"hello1" or "Foo.hello1" to a the instance member?

class Foo:
def hello1(self, p):
print 'hello1', p
def hello2(self, p):
print 'hello2', p
def dispatch(self, func, p):
func(self,p)

f=Foo()
f.dispatch(Foo.hello1, 23)
f.dispatch(Foo.hello1, 24)

f.dispatch_as_string("hello1", 23) ## this is what I want to do.

Many TIA and apologies if this is a FAQ, I googled and couldn't
find the answer.



Use getattr; add exception handling as needed. E.g.,


class Foo(object):
def __init__(self):
self.fake = None
def hello1(self, p):
print 'hello1', p
def hello2(self, p):
print 'hello2', p
def dispatch_as_string(self, fname, p):
try:
inst_method=getattr(self, fname)
inst_method(p)
except AttributeError:
# maybe no such attribute
raise
except TypeError:
# maybe the attribute is not callable (wrong type)
raise


f = Foo()
f.dispatch_as_string('hello1', 12)
 

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

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,247
Members
46,844
Latest member
JudyGvh32

Latest Threads

Top