2011-07-20 14 views
43

Piszę program w języku Python dla zabawy, ale utknąłem próbując zaimportować funkcję z klasy do innego pliku. Tu jest mój kodu:Importowanie funkcji z klasy do innego pliku?

#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() 

chcę wrócić funkcję o nazwie run() z klasy w innym pliku. Kiedy importuję plik, najpierw uruchamia on klasę z run(), a następnie uruchamia oryginalny kod. Dlaczego to się dzieje?

Oto kod z 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

Proszę pokazać, co w inny plik. Czy przeczytałeś [to] (http://docs.python.org/tutorial/modules.html)? – jtbandes

+0

To nie powinno nawet parsować - twoje wcięcie jest złe, a nawet obudowa różni się w zależności od miejsca. –

+0

Działa, dodałem kilka wcięć przez pomyłkę podczas kopiowania z textmate. naprawiono go w ostatniej edycji – Capkutay

Odpowiedz

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 

Zmień koniec systemu łączności do:

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

To te linie są zawsze run, które powodują, że będzie działać, gdy importowane, a także po uruchomieniu.

+0

, więc muszę umieścić wystąpienie klasy w oryginalnym pliku (jurassicpark mainframe)? mam to, spróbuję ... – Capkutay

+0

przy okazji, proszę wybaczyć naukowy temat tego programu, nie mogłem naprawdę wymyślić cokolwiek innego do zrobienia – Capkutay

+0

Sprawdź moją edycję - musisz tylko zrobić ostatni dwie linie twojego modułu, jeśli jest to, co jest wykonywane bezpośrednio. – agf

0

Naprawdę pomógłbyś, gdybyś zawarł kod, który nie działa (z pliku "innego"), ale podejrzewam, że możesz zrobić to, co chcesz, ze zdrową dawką funkcji "eval".

Na przykład:

def run(): 
    print "this does nothing" 

def chooser(): 
    return "run" 

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

Selektor zwraca nazwę funkcji do wykonania, eval następnie zamienia ciąg do rzeczywistej kod wykonywany w miejscu, a nawiasy wykończyć wywołanie funkcji.

+0

Masz dodatkową pojedynczą wycenę, dzięki czemu Twój program ma błąd składni. Ponadto, nie sądzę, żeby potrzebował 'eval' do tego, co robi, prawdopodobnie po prostu' getattr (module_or_class, chooser()) 'jeśli poprawnie interpretujesz jego pytanie. – agf

+0

Mogę wymyślić pół tuzina sposobów na zrobienie tego, co myślę, że on chce zrobić, niektóre mniej pythonesque niż inne. Jednak eval jest brutalnie łatwy w użyciu, choć czasem bardzo niebezpieczny. Jest całkiem możliwe, że po prostu musi zwrócić instancję klasy do innego pliku i uruchomić tę funkcję zgodnie z sugestią. Więcej szczegółów byłoby świetnie. – mikebabcock

2

Najpierw upewnij się, że oba pliki znajdują się w tym samym katalogu roboczym. Następnie możesz zaimportować cały plik. Na przykład:

import myClass 

lub możesz zaimportować całą klasę i całe funkcje z pliku. Na przykład:

from myClass import 

Na koniec należy utworzyć instancję klasy z oryginalnego pliku i wywołać obiekty instancji.

4

Jeśli, tak jak ja, chcesz utworzyć pakiet funkcji lub coś, co ludzie mogą pobrać, to jest to bardzo proste. Wystarczy napisać swoją funkcję w pliku Pythona i zapisać ją jako nazwę, którą chcesz W KATALOGU PYTHON. Teraz w skrypcie, w którym chcesz korzystać z tego, należy wpisać:

from FILE NAME import FUNCTION NAME 

Uwaga - w części, gdzie są literami wpisać nazwę pliku i nazwę stanowiska.

Teraz po prostu używaj swojej funkcji, jakkolwiek miała być.

przykład:

funkcji skryptowej - pamięć C: \ Python27 jak function_choose.py

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

SCRIPT użyciem funkcji - zapisane gdziekolwiek

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

wyjście zostanie psa, kota, lub kurczaka

nadzieję, że to pomogło, teraz można tworzyć pakiety funkcji do pobrania!

-------------------------------- Jest to dla Python 2.7 --------- ----------------------------

7
from FOLDER_NAME import FILENAME 
from FILENAME import CLASS_NAME FUNCTION_NAME 

FILENAME jest w/o przyrostkiem

Powiązane problemy