gpt4 book ai didi

python - 如何将文件的局部变量导入到当前模块

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:47 24 4
gpt4 key购买 nike

我的模块 MetaShrine.py 中有这个函数

我无法使用局部变量first_name_signup。错误是

NameError: name 'first_name_signup' is not defined

我不想让每个变量都是全局的。有没有办法可以导入另一个文件的局部变量而不将其设为全局变量?

这是我的主模块 MetaShrine.py 中的函数之一

def creating():

first_name_signup = input("Enter Your First Name\n")
password_signup = input("Creat a Password\n")

当我将此模块导入到新模块时,使用:

from MetaShrine import *

class test(unittest.TestCase):

def test_creating(self):
self.assertIsInstance(first_name_signup, str)

if __name__ == "__main__":
unittest.main()

...我明白了:

NameError: name 'first_name_signup' is not defined

最佳答案

基本上,返回值并将其放入另一个文件中的另一个变量中。这是我能想到的最好的办法了。

def creating():

first_name_signup = input("Enter Your First Name\n")
password_signup = input("Creat a Password\n")

return first_name_signup, password_signup

第二个文件:

import MetaShrine 

class test(unittest.TestCase):

def test_creating(self):
first_name_signup, password_signup = MetaShrine.creating()

self.assertIsInstance(first_name_signup, string)

if __name__ == "__main__":
unittest.main()

关于python - 如何将文件的局部变量导入到当前模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54386374/

24 4 0
文章推荐: c# - 如何通过最高 ID 获取 List 中的值?