471,573 Members | 1,238 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,573 software developers and data experts.

mapping a string to an instancemethod

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.

--
Mark Harrison
Pixar Animation Studios
Aug 1 '08 #1
1 1197
In article <7w******************@nlpi067.nbdc.sbc.com>, mh@pixar.com
wrote:
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.
Do what's below. Then learn about *args to make a version that
works with variable numbers of parameters...

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

f = Foo()
f.dispatch_as_string('hello1', 'world')
Many TIA and apologies if this is a FAQ, I googled and couldn't
find the answer.
--
David C. Ullrich
Aug 1 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.