split python source code into multiple files?

后端 未结 4 1656
轮回少年
轮回少年 2021-01-30 08:02

I have a code that I wish to split apart into multiple files. In matlab one can simply call a .m file, and as long as it is not defined as anything in particular it

4条回答
  •  没有蜡笔的小新
    2021-01-30 08:37

    Sure!

    #file  -- test.py --
    myvar = 42
    def test_func():
        print("Hello!")
    

    Now, this file ("test.py") is in python terminology a "module". We can import it (as long as it can be found in our PYTHONPATH) Note that the current directory is always in PYTHONPATH, so if use_test is being run from the same directory where test.py lives, you're all set:

    #file -- use_test.py --
    import test
    test.test_func()  #prints "Hello!"
    print (test.myvar)  #prints 42
    
    from test import test_func #Only import the function directly into current namespace
    test_func() #prints "Hello"
    print (myvar)     #Exception (NameError)
    
    from test import *
    test_func() #prints "Hello"
    print(myvar)      #prints 42
    

    There's a lot more you can do than just that through the use of special __init__.py files which allow you to treat multiple files as a single module), but this answers your question and I suppose we'll leave the rest for another time.

提交回复
热议问题