Python: How can I use variable from main file in module?

后端 未结 4 1797
死守一世寂寞
死守一世寂寞 2020-12-09 22:09

I have 2 files main.py and irc.py.
main.py

import irc
var = 1
func()

irc.py

def func():
    print var

相关标签:
4条回答
  • 2020-12-09 22:31

    Two options.

    from main import var
    
    def func():
        print var
    

    This will copy a reference to the original name to the importing module.

    import main
    
    def func():
        print main.var
    

    This will let you use the variable from the other module, and allow you to change it if desired.

    0 讨论(0)
  • 2020-12-09 22:40

    Well, that's my code which works fine:

    func.py:

    import __main__
    def func():
        print(__main__.var)
    

    main.py:

    from func import func
    
    var="It works!"
    func()
    var="Now it changes!"
    func()
    
    0 讨论(0)
  • 2020-12-09 22:50

    Don't. Pass it in. Try and keep your code as decoupled as possible: one module should not rely on the inner workings of the other. Instead, try and expose as little as possible. In this way, you'll protect yourself from having to change the world every time you want to make things behave a little different.

    main.py

    import irc
    var = 1
    func(var)
    

    irc.py

    def func(var):
        print var
    
    0 讨论(0)
  • 2020-12-09 22:56

    Well, var in the function isn't declared. You could pass it as an argument. main.py

    import irc
    var = 1
    func(var)
    

    irc.py

    def func(str):
        print str
    
    0 讨论(0)
提交回复
热议问题