簡體   English   中英

如何從另一個文件中打印python中的變量

[英]how can I print variable in python from another file

我有兩個文件,第一個是:test.py:

age_var = 22

def first_code():
   var1 = 'phone'
   var2= 'name'
   var3= 'last_name'
   there are more code down ...........

在第二個中,我只想在 test2.py 文件中打印 var1 和 age_var:

from dir.test import *

print(var1)
print(age_var)

我怎樣才能做到這一點?

由於var1是在first_code中定義的,因此您需要讓該函數return var1 ,然后從另一個模塊調用該函數,以便var1將被定義然后返回。

# First file

age_var = 22

def first_code():
    var1 = 'phone'
    var2= 'name'
    var3= 'last_name'
    # more code...
    return var1


# Second file

from dir.test import age_var, first_code

print(first_code())  # this is var1, because first_code returns it
print(age_var)       # this was imported from dir.test

您需要將要在該函數之外使用的所有變量設為全局變量,您可以這樣做

def first_code():
    global var1
    var1 = 'phone'
    etc...

然后如果 test 和 test2 在同一個目錄中,則通過執行此操作將 test.py 文件導入 test2.py

from test import *

如果 test 和 test2 在不同的目錄中,請執行此操作,首先確保包含 test.py 的目錄有一個名為__init__.py的文件,此文件可以為空,這樣 python 就知道該目錄是一個包,然后導入它就像這個

from directory.name.fileName import *

所以在你的情況下

from directory.name.test import *

請記住將directory.name更改為您的目錄,將所有 /s 替換為 .s

希望這可以幫助 :)

暫無
暫無

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

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