【问题标题】:Why is my python class being executed twice?为什么我的 python 类被执行了两次?
【发布时间】:2021-11-19 20:10:35
【问题描述】:

我目前正在尝试编写一个脚本,该脚本接受用户输入,然后通过位于另一个文件中的类将其打印出来。但是在运行我的脚本时,我必须给程序输入两次,然后由于奇怪的原因被打印三次。我还在stackoverflow上搜索了一些其他类似的问题,但没有一个能帮助我解决我的问题。

这是第一个文件中的代码:

#this is main.py
global test_input    
test_input = input('give me an input: ')
if 'i like cookies' in test_input:   
    from test import *
    test_class.test()

这是第二个文件中的代码:

#this is test.py
class test_class():
    def test():
        from main import test_input
        print(test_input)

运行脚本后的输出是什么样的:

give me an input: i like cookies
give me an input: i like cookies #this second input is created because the function is being executed twice. In this example I would've typed in i like cookies twice
i like cookies
i like cookies 
i like cookies 

输出应该是什么样子:

give me an input: i like cookies
i like cookies

如果有人能帮助我解决这个问题并向我解释我做错了什么,我会非常高兴:)

提前感谢您的每一个建议和帮助:)

【问题讨论】:

    标签: python python-3.x class


    【解决方案1】:

    它会因不良的编程习惯而惩罚您。 ;) 问题是,当您运行程序时,该模块不被视为已导入。因此,当您进入test_class.test() 时,您的from main 语句实际上会导致您的主程序再次被加载。它将再次进行输入调用,并再次调用test_class.test()。这次main已经导入了,不用再做,一切正常。

    子模块尝试从主模块导入某些内容是一种可怕的做法。如果您的模块函数需要一个值,则将其作为参数传递。

    【讨论】:

    • ooo 好的理解:) 非常感谢您的帮助和努力:) 这为我解决了问题:D
    • 几乎在您使用global 关键字的任何时候,它都预示着某些事情即将发生可怕的错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 2013-01-27
    • 1970-01-01
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多