Calling a method with a variable name

S

Simon Mullis

Hi All,

I'm collating a bunch of my utility scripts into one, creating a
single script to which I will symbolic link multiple times. This way
I only have to write code for error checking, output-formatting etc a
single time.

So, I have

~/bin/foo -> ~/Code/python/mother_of_all_utility_scripts.py
~/bin/bar -> ~/Code/python/mother_of_all_utility_scripts.py
~/bin/baz -> ~/Code/python/mother_of_all_utility_scripts.py

I would like "bar" to run the bar method (and so on).

-------------
class Statistic()
def __init__(self):
pass

def foo(self):
return "foo!"

def bar(self):
return "bar!"

# ... and so on...

def main():
stats_obj = Statistic()
name = re.sub("[^A-Za-z]", "", sys.argv[0])
method = getattr(stats_obj, name, None)
if callable(method):
stats_obj.name() # <------------HERE
else:
print "nope, not sure what you're after...."
-----------

However, as I'm sure you've all noticed already, there is no method
called "name". I would really prefer to get a nudge in the right
direction before I start evaling variables and so on.

Does my approach make sense? If not, please give me a hint...

Thanks

SM
 
D

Diez B. Roggisch

Simon said:
Hi All,

I'm collating a bunch of my utility scripts into one, creating a
single script to which I will symbolic link multiple times. This way
I only have to write code for error checking, output-formatting etc a
single time.

So, I have

~/bin/foo -> ~/Code/python/mother_of_all_utility_scripts.py
~/bin/bar -> ~/Code/python/mother_of_all_utility_scripts.py
~/bin/baz -> ~/Code/python/mother_of_all_utility_scripts.py

I would like "bar" to run the bar method (and so on).

-------------
class Statistic()
def __init__(self):
pass

def foo(self):
return "foo!"

def bar(self):
return "bar!"

# ... and so on...

def main():
stats_obj = Statistic()
name = re.sub("[^A-Za-z]", "", sys.argv[0])
method = getattr(stats_obj, name, None)
if callable(method):
stats_obj.name() # <------------HERE
else:
print "nope, not sure what you're after...."
-----------

However, as I'm sure you've all noticed already, there is no method
called "name". I would really prefer to get a nudge in the right
direction before I start evaling variables and so on.

Does my approach make sense? If not, please give me a hint...

You are almost there. Why don't you do

if callable(method):
method()

?

Diez
 

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,764
Messages
2,569,567
Members
45,042
Latest member
icassiem

Latest Threads

Top