簡體   English   中英

使用Python在其他模塊中導入函數的返回值時出錯

[英]Error when importing the returned value of a function in a different module using Python

我有一個文件( calculations ),該文件具有一個定義為number函數,執行該函數時其返回值為i 現在,我在另一個文件中定義了一個函數,並希望輸出值i 但是,當我嘗試“導入” i ,收到一條錯誤消息,提示i無法導入。

這是我的代碼(如果i是應該從功能進口number是在定義calculations

import calculations

def myfunction():
    calculations.number()
    print(calculations.i)

顯然,執行不帶print(calculations.i)語句的myfunction()可以成功運行。 但是,當我嘗試按照相同的方法導入i ,事實並非如此。 我也嘗試過使用from calculations import i ,盡管它也不起作用。 這可能與以下事實有關:上次在number()函數中“提及”它的情況為return i (盡管這可能不是問題),或者與它不屬於calculations文件本身有關,但這在該文件中存儲的功能之一的定義之內...

無論如何,發生了什么以及如何導入該值?

編輯:這是文件calculations的代碼:

def number():
    a = 2
    i = 0
    while a < 100
        a = a + 2
        i = i+1
    return i

您不能導入該函數本地的變量,以下是一些可以使用該變量的方法

解決方案1:

這是文件計算中的代碼:

def number():
    a = 2
    i = 0
    while a < 100
        a = a + 2
        i = i+1
    return i

您可以在myfunction中調用數字並將其分配給某個變量,假設我

import calculations

def myfunction():
    i = calculations.number()
    print(i)

解決方案2:

或者您可以這樣做:

這是文件計算中的代碼:

i = number()
def number():
    a = 2
    j = 0
    while a < 100
        a = a + 2
        j = j+1
    return j

你的功能

import calculations
def myfunction():
    print(calculations.i)

解決方案3:

或者您可以這樣做:

這是文件計算中的代碼:

global i = 0
def number():
    a = 2
    while a < 100
        a = a + 2
        i = i+1
    return i

你的功能

import calculations
def myfunction():
    print(calculations.i)

暫無
暫無

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

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