I need to figure out a way to convert a string in python to a namespace that can carry an integer value. This is important for a script I'm writing that creates a character sheet for a pen and paper roleplaying game that uses stat adjusted target numbers- I'm writing it in modules, and each stat calls one of these modules using a different version of a name in the same initial string, which is supposed to be converted to a namespace, then used to carry an integer that is used to modify another integer in a class.
问问题
1287 次
1 回答
1
听起来你想使用__import__
:
mod = __import__(name)
print mod.something
这允许您使用任意字符串name
作为要导入的模块的名称。您可以创建一个名为 example 的模块foo.py
,其中包含:
something = 4
然后上面的代码将打印 4 如果name
是"foo"
。
然而,这是 Python 中一种不常见的编程技术(如文档中所述),因此可能有更好的方法来表达您的意图。
于 2012-11-18T06:30:58.640 回答