2011-07-20 8 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()のクラスが実行され、元のコードが実行されます。なぜこれが起こるのですか?それは、常にそれがときに実行されるように引き起こしている、実行されているこれらの行だ

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

#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 

変更COMMシステムの終わりに:ここで

はcomm_systemからのコードがありますインポートされたときと実行されたとき。

+0

を読んだので、元のファイル(jurassicparkメインフレーム)にクラスのインスタンスを置く必要がありますか?それを試してみましょう... – Capkutay

+0

このプログラムのぎこちない主題を許してください、私は本当に何か他のことを考えることができませんでした – Capkutay

+0

私の編集をチェックしてください - あなたは最後に行う必要がありますそれが直接実行されている場合は、2行のモジュールが必要です。 – agf

0

( 'other'ファイルからの)動作しないコードを含めると、本当に役立つでしょうが、私はあなたが健康な量の 'eval'関数を使いたいと思っています。例えば

は:

def run(): 
    print "this does nothing" 

def chooser(): 
    return "run" 

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

チューが実行する機能の名前を返し、評価は、次にその場で実行される実際のコードに文字列をオン、および括弧は、関数呼び出しを仕上げます。

+0

プログラムに構文エラーがあるような特別な引用符があります。また、私は彼が自分のやっていることに対して 'eval'が必要ではないと思っています。正しく質問を解釈しているなら、おそらく' getattr(module_or_class、chooser()) 'でしょう。 – agf

+0

私は彼がやりたいと思うことをやり遂げる方法は半ダースと思うことができます。しかし、「eval」は時には非常に危険ですが、残酷に扱いやすいです。クラスのインスタンスを別のファイルに返すだけで、あなたが提案したとおりにそこから関数を実行するだけです。詳細は素晴らしいでしょう。 – mikebabcock

2

まず、両方のファイルが同じ作業ディレクトリにあるかどうかを確認する必要があります。次に、ファイル全体をインポートすることができます。たとえば、

import myClass 

などです。また、ファイル全体からクラスと関数全体をインポートすることもできます。たとえば、

from myClass import 

最後に、元のファイルからクラスのインスタンスを作成し、インスタンスオブジェクトを呼び出す必要があります。

4

私のように、人々がダウンロードできる機能パックなどを作成したい場合、それは非常に簡単です。あなたの関数をPythonファイルに書いて、あなたのPYTHON DIRECTORYに入れたい名前で保存してください。さて、あなたがこれを使用するスクリプトでは、次のように入力:

from FILE NAME import FUNCTION NAME 

注意を - あなたは、ファイル名や関数名を入力する場所大文字で部品があります。

今はあなたの機能を使用していますが、それは意図されていました。

例:

機能SCRIPT - Cで保存された:\ Python27 function_chooseとして。PY

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

SCRIPT使用して関数 -

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

OUTPUTは、犬、猫、またはニワトリ

になりますどこに保存されたが、これは助けを望んだ、今はダウンロードのための機能パックを作成することができます!

--------------------------------これはPython 2.7用です--------- ----------------------------

7
from FOLDER_NAME import FILENAME 
from FILENAME import CLASS_NAME FUNCTION_NAME 

FILENAMEは、W/Oサフィックス

関連する問題