如何从另一个文件中打印在Python中的变量

发布于 2025-02-08 19:27:06 字数 313 浏览 2 评论 0原文

我有第一个文件是:test.py:

age_var = 22

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

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

from dir.test import *

print(var1)
print(age_var)

我该怎么做?

I have tow files the first one is: test.py:

age_var = 22

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

In the second one I Want to print var1 and age_var only, in the test2.py file:

from dir.test import *

print(var1)
print(age_var)

How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暗喜 2025-02-15 19:27:07

由于var1是在first_code中定义的,因此您需要拥有该函数返回var1,然后 call 来自另一个模块的函数,以便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

Since var1 is defined inside first_code, you'll need to have that function return var1, and then call the function from the other module so that var1 will get defined and then returned.

# 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
浮世清欢 2025-02-15 19:27:06

您需要使所有要在该功能之外使用的变量全局使用,可以通过执行此操作

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

,然后通过执行test.py文件将其导入到test2.py

from test import *

中test和test2在不同的目录中,首先确保具有test.py的dir具有一个称为__ init __. py此文件可以为空的文件下一个这样的导入

from directory.name.fileName import *

,因此在您的情况下,

from directory.name.test import *

请记住将directory.name更改为您的目录替换所有
/s with .s

希望这有帮助:)

you need to make all the variables global that you want to use outside of that function you can do that by doing

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

and then import the test.py file into test2.py by doing this if test and test2 are in the same dir

from test import *

do this if test and test2 are in different directories, first make sure that the dir that has test.py has a file called __init__.py this file can be empty, this is so python know that that dir is a package next import it like this

from directory.name.fileName import *

so in your case

from directory.name.test import *

remember to change directory.name to your directory replacing all the
/s with .s

hope this helps :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文