2017-01-21 26 views
-3

我在用Python構建一個測驗。所以代碼看起來像這樣。Python測驗問題,我可以從另一個文件導入整個「已定義的函數」嗎?

def animal_quiz(): 
    # do something 

def city_quiz(): 
    # do something 

def math_quiz(): 
    # do something 

topic = raw_input('Do you want to answer questions on animals or capital cities or math? Type animal, city or math') 

if topic == 'animal': 
    animal_quiz() 

elif topic == 'city': 
    city_quiz() 

但是,這是可能的,如果我想在不同的文件中定義了整個「動物測驗」的功能,則只需導入該文件..什麼?怎麼樣?

+1

Python提供了一個名爲 「進口」 要做到這一點的機制。任何基本的Python教程都應該涵蓋這個。 – augurar

+1

是的,實際上它應該是任何體面教程的一部分。例如https://docs.python.org/3/tutorial/modules.html#more-on-modules。我想你會發現閱讀教程的速度要快於問問題! – tdelaney

+0

可能重複的[如何從另一個文件調用函數?](http://stackoverflow.com/questions/7701646/how-to-call-a-function-from-another-file) –

回答

0

是有可能

from my_file import func 
func() 

import my_file 
my_file.func() 

搜索Python模塊

+0

非常感謝taoufik。那幫了我很多。 –

相關問題