Import Python Script Into Another?

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 says that we don't have to import them to pass the test, but I'm curious as to how we would do so.

Link to the lesson | Link to the code to correct

And here are the particular lines of code that call on a previous script:

words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)

print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
print sorted_words
print_first_and_last(sentence)
print_first_a_last_sorted(sentence)

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 symbols 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 symbols (functions, classes, etc) in other directories or inside modules.


值得一提的是(至少在python 3中),为了能够工作,你必须在同一个目录下有一个名为__init__.py的文件。

链接地址: http://www.djcxy.com/p/54824.html

上一篇: Django导入错误:没有名为apps的模块

下一篇: 导入Python脚本到另一个?