[英]Call a specific function defined in different .py file from another .py file using user input
我有一個包含一些函數的.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_Suites'
請提供一些有關如何解決此問題的見解。 謝謝
在您的代碼string
是一個字符串,其中包含您要調用的函數的名稱。 ob.string()
在對象ob
上查找函數namend字符串。 要從對象obj
獲取具有名稱name
的屬性,請使用getattr(obj, name)
,因此在您的情況下:
getattr(ob, string)()
同樣正如Tagc在評論中指出的那樣eval
在你使用它的方式上是一個壞主意。 而是使用user_input=int(input("enter the test case number"))
,它將給定的字符串解析為整數。
如果您需要更靈活的東西,可以使用ast模塊中的 ast.literal_eval
,它也可以解析列表,dicts,...( 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()
#...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.