使用字符串作为变量名

7

有没有办法使用字符串来调用类的方法?以下是一个示例,希望能更好地解释(使用我认为应该的方式):

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

str = "world"
hello = helloworld()

hello.`str`()

这将输出Hello World!

谢谢提前。


输出应该是 "hello world" 还是 "Hello World!"? - Buddy
4个回答

16
你可以使用 getattr
>>> class helloworld:
...     def world(self):
...         print("Hello World!")
... 
>>> m = "world"
>>> hello = helloworld()
>>> getattr(hello, m)()
Hello World!
  • 请注意,你示例中class helloworld()中的括号是不必要的。
  • 并且,正如SilentGhost指出的那样,str是一个不幸的变量名。

4
"str" 不是一个好的变量名选择。 - SilentGhost

2

警告:exec是一种危险的函数,在使用前请进行研究

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

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

3
这真的不是一个好主意。在可能的情况下,应该避免使用exec。getattr就是为解决这个问题而设计的。 - Stephan202
2
不要混淆如何做某件事与它是否安全。exec确实是一个危险的函数。然而,有办法可以安全地使用它。在这种情况下,您可以传递“globals”和“locals”上下文字典,以便在“沙盒”中运行exec。 - AgentLiquid
1
我听说过exec()的糟糕之处,但是它却完美地工作了。 - Steve Gattuso
注意,Sliggy,exec确实是一个危险的使用。在处理它之前,请确保您充分理解这个武器。 - AgentLiquid

-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()。


2
通过调用blah,你如何获得thing1的输出? - a_m0d

-3
你要找的是 exec
class helloworld():
    def world(self):
        print "Hello World!"

str = "world"
hello = helloworld()

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

exec(completString)

我以前从未使用过"exec",但我想我会重新考虑一下... 升级。 - Peter Ericson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接