繁体   English   中英

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

[英]How to import local variables of a file to current module

我的模块 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 中编写单元测试的正确和 pythonic 方法是从实际模块导入classesmethodsfunctions ,然后在导入的对象上运行测试,而不是从模块中实际导入return值或变量。

所以在你的情况下它应该看起来像

代码.py

def creating():

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

    return first_name_signup, password_signup

测试.py

import MetaShrine import creating
import unittest

class test(unittest.TestCase):

    def test_creating(self):
    # actual assert statement for the test case, i.e.
    result, _ = creating()
    self.assertEqual(result, 'some_name')


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM