使用string作为变量名

时间:2009-06-17 22:27:23

标签: python

我有什么方法可以使用字符串来调用类的方法吗?这是一个有希望更好地解释的例子(使用我认为的方式):

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

str = "world"
hello = helloworld()

hello.`str`()

哪会输出Hello World!

提前致谢。

4 个答案:

答案 0 :(得分:16)

您可以使用getattr

>>> class helloworld:
...     def world(self):
...         print("Hello World!")
... 
>>> m = "world"
>>> hello = helloworld()
>>> getattr(hello, m)()
Hello World!
  • 请注意,在这种情况下,您的示例中的class helloworld()中的parens是不必要的。
  • 而且,正如SilentGhost指出的那样,str是变量的一个不幸名称。

答案 1 :(得分:2)

警告:exec是一个危险的功能,在使用之前进行研究

您还可以使用内置函数“exec”:

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

答案 2 :(得分:-3)

一种方法是你可以将变量设置为与数据

相同的函数
def thing1():
    print "stuff"

def thing2():
    print "other stuff"

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

输出的结果是

stuff
other stuff

然后你可以变得更复杂并且有

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

等等。如果要将模块方法自动编译到字典中,请使用dir()

答案 3 :(得分:-3)

您正在寻找的是exec

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

str = "world"
hello = helloworld()

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

exec(completString)