[英]Passing a variable inside of a function to another Python file
I have a two python files which are classification_model.py
and result.py
. 我有两个python文件,分别是
classification_model.py
和result.py
。 There is a function in classification_model.py
file as 在
classification_model.py
文件中有一个函数
def learningbased():
ann_accuracy = (metrics.accuracy_score(expected, predicted))
I want to get this ann_accuracy
variable into result.py
file.I used 我想把这个
ann_accuracy
变量放到result.py
文件中。我用过
from classification_model import *
from classification_model import learningbased
But it doesn't work. 但它不起作用。 Can anyone tell me how can I do this.
谁能告诉我怎么能这样做呢。
good way: You can return the value of ann_accuracy in the function and call the function in result.py to get the value. 好方法:你可以在函数中返回ann_accuracy的值,并调用result.py中的函数来获取值。
#classification_model.py:
def learningbased():
ann_accuracy = (metrics.accuracy_score(expected, predicted))
return ann_accuracy
#result.py
from classification_model import *
ann_accuracy = learningbased()
alternate way (use when desparate, no other solution): declare ann_accuracy as a global variable in classification_model.py. 替代方式(在绝望时使用,没有其他解决方案):将ann_accuracy声明为classification_model.py中的全局变量。 That way when you do
from classification_model import *
and call the function, you'll get the global variable in result.py 这样当你
from classification_model import *
调用函数时,你将获得result.py中的全局变量
I think you should declare your project as a package, by adding a __init__.py
file : 我认为您应该通过添加
__init__.py
文件将项目声明为包:
project_folder
|_ __init__.py
|_ classification_model.py
|_ result.py
After doing that, in result.py
you can do : 完成后,在
result.py
你可以这样做:
from . import classification_model
classification_model.learning_based()
It's a little different from what was already suggested and it enables you to have a clear organisation of your project. 它与已经建议的内容略有不同,它使您能够清楚地组织项目。
Declare ann_accuracy as a global variable in classification_model.py. 将ann_accuracy声明为classification_model.py中的全局变量。 Use
from classification_model import *
, you can use/access the global variable in result.py. 使用
from classification_model import *
,您可以在result.py中使用/访问全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.