I'm writing a Python program for fun but got stuck trying to import a function from a class in another file. Here is my code:
我正在编写一个有趣的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()
I want to return a function called run()
from a class in another file. When I import the file, it first runs the class with run()
in it, then proceeds to run the original code. Why does this happen?
我想从另一个文件中的类返回一个名为run()的函数。当我导入文件时,它首先运行带有run()的类,然后继续运行原始代码。为什么会这样?
Here is the code from comm_system:
这是来自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()
6 个解决方案
#1
69
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
Change the end of comm system to:
将comm系统的结尾更改为:
if __name__ == '__main__':
a_game = Comm_system()
a_game.run()
It's those lines being always run that are causing it to be run when imported as well as when executed.
这些行总是在运行时导致它在导入时以及在执行时运行。
#2
8
from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME
FILENAME is w/o the suffix
FILENAME没有后缀
#3
4
If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:
如果像我一样,你想制作一个功能包或人们可以下载的东西,那么它就非常简单。只需在python文件中编写您的函数,并将其保存为您在PYTHON PIRTHON目录中的名称。现在,在您要使用它的脚本中键入:
from FILE NAME import FUNCTION NAME
Note - the parts in capital letters are where you type the file name and function name.
注 - 大写字母部分是您键入文件名和函数名的位置。
Now you just use your function however it was meant to be.
现在你只是使用你的功能,但它本来就是。
Example:
例:
FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py
功能脚本 - 在C:\ Python27中保存为function_choose.py
def choose(a):
from random import randint
b = randint(0, len(a) - 1)
c = a[b]
return(c)
SCRIPT USING FUNCTION - saved wherever
使用功能的脚本 - 保存在任何地方
from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))
OUTPUT WILL BE DOG, CAT, OR CHICKEN
输出将是狗,猫或鸡
Hoped this helped, now you can create function packs for download!
希望这有帮助,现在您可以创建下载功能包!
--------------------------------This is for Python 2.7-------------------------------------
--------------------------------这是为Python 2.7 ------------- ------------------------
#4
2
First you need to make sure if both of your files are in the same working directory. Next, you can import the whole file. For example,
首先,您需要确保两个文件是否在同一个工作目录中。接下来,您可以导入整个文件。例如,
import myClass
or you can import the entire class and entire functions from the file. For example,
或者您可以从文件中导入整个类和整个函数。例如,
from myClass import
Finally, you need to create an instance of the class from the original file and call the instance objects.
最后,您需要从原始文件创建该类的实例并调用实例对象。
#5
0
It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.
如果您包含不起作用的代码(来自“其他”文件)会非常有用,但我怀疑您可以通过'eval'功能的健康剂量来做您想做的事情。
For example:
例如:
def run():
print "this does nothing"
def chooser():
return "run"
def main():
'''works just like:
run()'''
eval(chooser())()
The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.
选择器返回要执行的函数的名称,eval然后将字符串转换为要在适当位置执行的实际代码,并且括号结束函数调用。
#6
-1
You can use the below syntax -
您可以使用以下语法 -
from FolderName.FileName import Classname
#1
69
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
Change the end of comm system to:
将comm系统的结尾更改为:
if __name__ == '__main__':
a_game = Comm_system()
a_game.run()
It's those lines being always run that are causing it to be run when imported as well as when executed.
这些行总是在运行时导致它在导入时以及在执行时运行。
#2
8
from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME
FILENAME is w/o the suffix
FILENAME没有后缀
#3
4
If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:
如果像我一样,你想制作一个功能包或人们可以下载的东西,那么它就非常简单。只需在python文件中编写您的函数,并将其保存为您在PYTHON PIRTHON目录中的名称。现在,在您要使用它的脚本中键入:
from FILE NAME import FUNCTION NAME
Note - the parts in capital letters are where you type the file name and function name.
注 - 大写字母部分是您键入文件名和函数名的位置。
Now you just use your function however it was meant to be.
现在你只是使用你的功能,但它本来就是。
Example:
例:
FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py
功能脚本 - 在C:\ Python27中保存为function_choose.py
def choose(a):
from random import randint
b = randint(0, len(a) - 1)
c = a[b]
return(c)
SCRIPT USING FUNCTION - saved wherever
使用功能的脚本 - 保存在任何地方
from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))
OUTPUT WILL BE DOG, CAT, OR CHICKEN
输出将是狗,猫或鸡
Hoped this helped, now you can create function packs for download!
希望这有帮助,现在您可以创建下载功能包!
--------------------------------This is for Python 2.7-------------------------------------
--------------------------------这是为Python 2.7 ------------- ------------------------
#4
2
First you need to make sure if both of your files are in the same working directory. Next, you can import the whole file. For example,
首先,您需要确保两个文件是否在同一个工作目录中。接下来,您可以导入整个文件。例如,
import myClass
or you can import the entire class and entire functions from the file. For example,
或者您可以从文件中导入整个类和整个函数。例如,
from myClass import
Finally, you need to create an instance of the class from the original file and call the instance objects.
最后,您需要从原始文件创建该类的实例并调用实例对象。
#5
0
It would really help if you'd include the code that's not working (from the 'other' file), but I suspect you could do what you want with a healthy dose of the 'eval' function.
如果您包含不起作用的代码(来自“其他”文件)会非常有用,但我怀疑您可以通过'eval'功能的健康剂量来做您想做的事情。
For example:
例如:
def run():
print "this does nothing"
def chooser():
return "run"
def main():
'''works just like:
run()'''
eval(chooser())()
The chooser returns the name of the function to execute, eval then turns a string into actual code to be executed in-place, and the parentheses finish off the function call.
选择器返回要执行的函数的名称,eval然后将字符串转换为要在适当位置执行的实际代码,并且括号结束函数调用。
#6
-1
You can use the below syntax -
您可以使用以下语法 -
from FolderName.FileName import Classname