使用用户inpu从另一个.py文件调用在不同的.py文件中定义的特定函数

2024-04-25 21:57:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含一些函数的.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”

请就如何解决这个问题提出一些见解。 谢谢


Tags: 文件函数testhelloinputheredefprint
2条回答

在代码中string是一个字符串,其中包含要调用的函数的名称。ob.string()在对象ob上查找函数namendstring。要从对象obj获取名为name的属性,请使用getattr(obj, name),因此在您的示例中:

getattr(ob, string)()

正如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通过函数名访问函数。你知道吗

#test_suites.py
def fun1():
    print("hello fun1 here")
def fun2():
    print("hello fun2 here")
def fun3():
    print("hello fun3 here")
def fun4():
  print("hello fun4 here")


import test_suites

func1 = getattr(test_suites, 'func1')
# call func1()
#...

相关问题 更多 >

    热门问题