Import Python Script Into Another?

后端 未结 5 1617
花落未央
花落未央 2020-11-28 23:59

I\'m going through Zed Shaw\'s Learn Python The Hard Way and I\'m on lesson 26. In this lesson we have to fix some code, and the code calls functions from another script. He

5条回答
  •  抹茶落季
    2020-11-29 00:51

    It depends on how the code in the first file is structured.

    If it's just a bunch of functions, like:

    # first.py
    def foo(): print("foo")
    def bar(): print("bar")
    

    Then you could import it and use the functions as follows:

    # second.py
    import first
    
    first.foo()    # prints "foo"
    first.bar()    # prints "bar"
    

    or

    # second.py
    from first import foo, bar
    
    foo()          # prints "foo"
    bar()          # prints "bar"
    

    or, to import all the names defined in first.py:

    # second.py
    from first import *
    
    foo()          # prints "foo"
    bar()          # prints "bar"
    

    Note: This assumes the two files are in the same directory.

    It gets a bit more complicated when you want to import names (functions, classes, etc) from modules in other directories or packages.

提交回复
热议问题