2011-07-20 88 views
43

我正在寫一個Python程序的樂趣,但卡住試圖從另一個文件中的類導入功能。這裏是我的代碼:從另一個文件中的類導入函數?

#jurassic park mainframe 

from random import randint 
from sys import exit 
from comm_system import Comm_system #the file i want to import from 



class Jpark_mainframe(object): 
    def mainframe_home(self): 
    print "=====Welcome to the Jurassic Park Mainframe=====" 
    print "==========Security Administration===============" 
    print "===========Communications Systems===============" 
    print "===============System Settings==================" 
    print "===================Quit=========================" 

    prompt = raw_input("What would you like to do? ") 

    while prompt != "Quit": 

     if prompt == "Security Administration": 
      print "Please enter the 5-digit passcode:" 
      security_passcode = "%d%d%d%d%d" % (2, 0, 1, 2, randint(1, 2)) 
      security_guess = raw_input(": ") 
      security_guesses = 0 

      while security_guess != security_passcode and security_guesses < 7: 
       print "Incorrect. Please enter the security passcode." 
       security_guesses += 1 
       security_guess = raw_input(": ") 

       if security_guess == security_passcode: 
        print "=========Security Administration=======" 
        print "Area 1 Fences: Off" 
        print "Area 2 Fences: On" 
        print "Area 3 Fences: Off" 
        print "Velociraptor Compound: Off" 
        print "Lobby Security System: Off" 
        print "Entrance Facility System: Off" 
        print "To enable all systems, enter 'On'" 


        enable_security = raw_input(": ") 

        if enable_security == "On": 
         print "Systems Online." 


     if prompt == "System Settings": 
      print "You do not have access to system settings." 
      exit(0) 


     if prompt == "Communications Systems": 
      print "===========Communications Systems===========" 
      print "error: 'comm_link' missing in directories" 
      exit(0) 
      return Comm_system.run #this is where I want to return the 
                #the other file 

the_game = jpark_mainframe() 
the_game.mainframe_home() 

我想從另一個文件中的類返回一個名爲run()的函數。當我導入文件時,它首先運行帶有run()的類,然後繼續運行原始代碼。爲什麼會發生?

下面是從comm_system代碼:

#communication systems 


from sys import exit 

class Comm_system(object): 
def run(self): 

    comm_directory = ["net_link", "tsfa_run", "j_link"] 
    print "When the system rebooted, some files necessary for" 
    print "communicating with the mainland got lost in the directory." 
    print "The files were poorly labeled as a result of sloppy" 
    print "programming on the staff's part. You must locate the" 
    print "the file and contact the rescue team before the dinosaurs" 
    print "surround the visitor's center. You were also notified the" 
    print "generators were shorting out, and the mainframe will lose" 
    print "power at any moment. Which directory will you search in?" 
    print "you don't have much time! Option 1: cd /comm_sys/file" 
    print "Option 2: cd /comm_sys/dis" 
    print "Option 3: cd /comm_sys/comm" 

    dir_choice = raw_input("jpark_edwin$ ") 

    if dir_choice == "/comm_sys/file" or dir_choice == "/comm_sys/dis": 
     print "misc.txt" 
     print "You couldn't locate the file!" 
     print "The system lost power and your computer shut down on you!" 
     print "You will not be able to reach the mainland until the system" 
     print "comes back online, and it will be too late by then." 
     return 'death' 

    if dir_choice == "/comm_sys/comm": 
     comm_directory.append("comm_link") 
     print comm_directory 
     print "You found the right file and activated it!" 
     print "Just in time too, because the computers shut down on you." 
     print "The phonelines are radios are still online." 
     print "You and the other survivors quickly call the mainlane" 
     print "and help is on the way. You all run to the roof and wait" 
     print "until the helocopter picks you up. You win!" 
a_game = Comm_system() 
a_game.run() 
+0

請出示什麼的其他文件。你有沒有讀[this](http://docs.python.org/tutorial/modules.html)? – jtbandes

+0

這甚至不應該被解析 - 你的縮進是錯誤的,甚至套管在不同地方都是不同的。 –

+0

它運行時,從textmate複製時,我錯誤地添加了幾個縮進。修復它在最後編輯 – Capkutay

回答

61
from otherfile import TheClass 
theclass = TheClass() 
# if you want to return the output of run 
return theclass.run() 
# if you want to return run itself to be used later 
return theclass.run 

更改通訊系統的末尾:

if __name__ == '__main__': 
    a_game = Comm_system() 
    a_game.run() 

正是這些線是始終運行所導致它被時運行導入以及執行時。

+0

所以我必須把類的實例放在原始文件(jurassicpark主機)?得到它,我會試一試... – Capkutay

+0

順便說一句,請原諒這個程序的令人討厭的主題,我真的想不出別的事情要做 – Capkutay

+0

看看我的編輯 - 你只需要做最後的如果它是直接執行的內容,那麼你的模塊有兩行。 – agf

0

如果你包含的代碼不能工作(來自'其他'文件),那真的會有幫助,但我懷疑你可以用'eval'函數的健康劑量來做你想做的。

例如:

def run(): 
    print "this does nothing" 

def chooser(): 
    return "run" 

def main(): 
    '''works just like: 
    run()''' 
    eval(chooser())() 

的選擇器返回到執行該功能的名稱,EVAL然後轉向一個字符串轉換成實際的代碼來就地執行,並且括號玩完函數調用。

+0

你有一個額外的單引號,使你的程序有語法錯誤。另外,如果你正確解釋他的問題,我認爲他不需要''eval'',可能只是'getattr(module_or_class,chooser())'。 – agf

+0

我可以想出六種方法來做我認爲他想做的事情,比其他人少一些pythonesque。然而,'eval'儘管有時非常危險,卻非常容易操作。很可能他只需要將一個類的實例返回到另一個文件,並按照您的建議從那裏運行該函數。更多的細節會很棒。 – mikebabcock

2

首先你需要確定你的兩個文件是否在同一個工作目錄下。接下來,您可以導入整個文件。例如,

import myClass 

或者您可以從文件中導入整個類和整個函數。例如,

from myClass import 

最後,您需要從原始文件創建類的實例並調用實例對象。

4

如果和我一樣,你想製作一個功能包或者人們可以下載的東西,那麼這很簡單。只需將你的函數寫入一個python文件,並將其保存爲您的PYTHON DIRECTORY中所需的名稱即可。現在,在你的腳本,你想用這個,你鍵入:

from FILE NAME import FUNCTION NAME 

注 - 大寫字母的部分,在那裏你鍵入文件名和函數名。

現在你只是使用你的功能,但它的意思是。

實施例:

FUNCTION SCRIPT - 保存在C:\ Python27作爲function_choose。PY

def choose(a): 
    from random import randint 
    b = randint(0, len(a) - 1) 
    c = a[b] 
    return(c) 

腳本中使用功能 - 保存到任何地方

from function_choose import choose 
list_a = ["dog", "cat", "chicken"] 
print(choose(list_a)) 

輸出將被狗,貓,或雞肉

希望這個幫,現在你可以創建功能包下載!

--------------------------------這是用於Python 2.7 --------- ----------------------------

7
from FOLDER_NAME import FILENAME 
from FILENAME import CLASS_NAME FUNCTION_NAME 

文件名是W/O後綴

相關問題