簡體   English   中英

從其他腳本導入功能

[英]import function from other scripts

我有以下腳本:

 src/
     __init__.py
     evaluation.py
     main.py

隨后是Evaluation.py的腳本,

from collections import Counter
def f_score(pred, answers):

     '''

     f1 = (2 * precision * recall) / (precision + recall)
     return f1

Evaluation.py包含一個名為“ f_score”的函數,我想在main.py中使用f_score函數

在main.py中,我執行以下操作:

 from evaluation import *
 f_score()

我收到錯誤消息:NameError:未定義名稱'f_score'。

但是,如果我這樣做

 from evaluation import f_score
 f_score()

這可行。 請問為什么?

您可能需要安裝最新的python更新。 當我嘗試時,它可以無縫運行。

from file1 import *
input = input("Enter:")
if input == "hi":
    hi_back()

這將打印出“ hi”,因為這是file1中的函數。

確保模塊位於相同的路徑,如前所述。 這是我從創建的模塊中導入內容的方式:

import file1 as f1
f1.function1()

這是我首選的處理方式,當您在一個文件中導入許多不同的模塊時,使工作變得更輕松。 我在您的代碼中看到函數中只有三個''',但沒有一個可以結束注釋。 這可能是一個問題,因為該功能會認為其中沒有任何內容。 還可能您有拼寫錯誤? 發生在我們當中最好的:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM