我有一个包含一些函数的.py文件。看来是这样例如:你知道吗
class Test_suites():
def fun1():
print("hello fun1 here")
def fun2():
print("hello fun2 here")
def fun3():
print("hello fun3 here")
def fun4():
print("hello fun4 here")
现在我有了另一个文件,它接收用户的输入,并尝试从第一个python调用该特定函数文件。它看例如:你知道吗
from test_suites import Test_Suites
ob=Test_Suites()
dictionary={1:'fun1',2:'fun2',3:'fun3',4:'fun4'}
user_input=eval(input("enter the test case number"))
string=dictionary[user_input]
ob.string()
但它抛出了一个错误:-ImportError:无法导入名称“Test\u Suites”
请就如何解决这个问题提出一些见解。 谢谢
在代码中
string
是一个字符串,其中包含要调用的函数的名称。ob.string()
在对象ob
上查找函数namendstring。要从对象obj
获取名为name
的属性,请使用getattr(obj, name)
,因此在您的示例中:正如Tagc在评论中指出的那样,
eval
在使用它的方式上是个坏主意。相反,使用user_input=int(input("enter the test case number"))
将给定字符串解析为整数。你知道吗如果您需要更灵活的东西,您可以使用ast module中的
ast.literal_eval
,它还可以解析列表、dict。。。(https://docs.python.org/3/library/ast.html#ast.literal_eval)如我在评论中所说,使用
getattr
通过函数名访问函数。你知道吗相关问题 更多 >
编程相关推荐