web-dev-qa-db-fra.com

Importer une fonction d'une classe dans un autre fichier?

J'écris un programme Python pour le plaisir, mais je me suis retrouvé coincé en essayant d'importer une fonction d'une classe dans un autre fichier. Voici mon code:

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

Je veux renvoyer une fonction appelée run() d'une classe dans un autre fichier. Lorsque j'importe le fichier, il exécute d'abord la classe avec run(), puis exécute le code d'origine. Pourquoi cela arrive-t-il? 

Voici le code de 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()
54
Capkutay
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

Changez le système de fin de communication en:

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

Ce sont ces lignes qui sont toujours exécutées qui le font fonctionner lors de l'importation et lors de l'exécution.

82
agf
from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME

FILENAME est sans le suffixe 

10
Alon Kogan

Si, comme moi, vous voulez créer un pack de fonctions ou quelque chose que les gens peuvent télécharger, c'est très simple. Écrivez simplement votre fonction dans un fichier python et enregistrez-la sous le nom de votre choix dans votre répertoire PYTHON. Maintenant, dans votre script où vous voulez utiliser ceci, vous tapez:

from FILE NAME import FUNCTION NAME

Remarque - les parties en majuscules sont les endroits où vous tapez le nom du fichier et le nom de la fonction.

Maintenant, vous utilisez simplement votre fonction comme il se doit.

Exemple:

FUNCTION SCRIPT - enregistré dans C:\Python27 sous le nom function_choose.py

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

SCRIPT UTILISING FUNCTION - sauvegardé partout

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

LA SORTIE SERA CHIEN, CHAT, OR POULET

Espéré que cela vous a aidé, vous pouvez maintenant créer des packs de fonctions à télécharger!

-------------------------------- Ceci est pour Python 2.7 ------------- ------------------------

4
James Hood

Vous devez d’abord vérifier que vos deux fichiers se trouvent dans le même répertoire de travail. Ensuite, vous pouvez importer le fichier entier. Par exemple,

import myClass

ou vous pouvez importer la classe entière et des fonctions entières du fichier. Par exemple,

from myClass import

Enfin, vous devez créer une instance de la classe à partir du fichier d'origine et appeler les objets d'instance.

Cela aiderait vraiment si vous incluiez le code qui ne fonctionnait pas (dans le fichier 'other'), mais je suppose que vous pourriez faire ce que vous voulez avec une bonne dose de la fonction 'eval'.

Par exemple:

def run():
    print "this does nothing"

def chooser():
    return "run"

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

Le sélecteur renvoie le nom de la fonction à exécuter, eval transforme ensuite une chaîne en code à exécuter sur place et les parenthèses achèvent l'appel de la fonction.

0
mikebabcock