Steve Gattuso
Steve Gattuso

Reputation: 7812

Using string as variable name

Is there any way for me to use a string to call a method of a class? Here's an example that will hopefully explain better (using the way I think it should be):

class helloworld():
    def world(self):
        print "Hello World!"

str = "world"
hello = helloworld()

hello.`str`()

Which would output Hello World!.

Thanks in advance.

Upvotes: 7

Views: 5307

Answers (4)

whatsisname
whatsisname

Reputation: 6140

one way is you can set variables to be equal to functions just like data

def thing1():
    print "stuff"

def thing2():
    print "other stuff"

avariable = thing1
avariable ()
avariable = thing2
avariable ()

And the output you'l get is

stuff
other stuff

Then you can get more complicated and have

somedictionary["world"] = world
somedictionary["anotherfunction"] = anotherfunction

and so on. If you want to automatically compile a modules methods into the dictionary use dir()

Upvotes: -3

AgentLiquid
AgentLiquid

Reputation: 3682

Warning: exec is a dangerous function to use, study it before using it

You can also use the built-in function "exec":

>>> def foo(): print('foo was called');
...
>>> some_string = 'foo';
>>> exec(some_string + '()');
foo was called
>>>

Upvotes: 2

crackity_jones
crackity_jones

Reputation: 1077

What you're looking for is exec

class helloworld():
    def world(self):
        print "Hello World!"

str = "world"
hello = helloworld()

completeString = "hello.%s()" % str

exec(completString)

Upvotes: -3

Stephan202
Stephan202

Reputation: 61469

You can use getattr:

>>> class helloworld:
...     def world(self):
...         print("Hello World!")
... 
>>> m = "world"
>>> hello = helloworld()
>>> getattr(hello, m)()
Hello World!
  • Note that the parens in class helloworld() as in your example are unnecessary, in this case.
  • And, as SilentGhost points out, str is an unfortunate name for a variable.

Upvotes: 16

Related Questions