导入Python脚本到另一个?

我正在经历Zed Shaw的“学习Python困难的方法”,我正在上课26.在本课中,我们必须修复一些代码,并且代码会从另一个脚本调用函数。 他说我们不需要导入它们来通过测试,但我很好奇我们会怎么做。

链接到课程| 链接到代码来纠正

以下是调用以前脚本的特定代码行:

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)

这取决于第一个文件中代码的结构。

如果它只是一堆功能,如:

# first.py

def foo(): print("foo")
def bar(): print("bar")

然后你可以导入它并使用如下函数:

# second.py
import first

first.foo()    # prints "foo"
first.bar()    # prints "bar"

要么

# second.py
from first import foo, bar

foo()          # prints "foo"
bar()          # prints "bar"

或者,要导入first.py中定义的所有符号:

# second.py
from first import *

foo()          # prints "foo"
bar()          # prints "bar"

注意:这假设这两个文件位于相同的目录中。

当你想要在其他目录或模块内导入符号(函数,类等)时,它会变得更加复杂。


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

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

上一篇: Import Python Script Into Another?

下一篇: What's the difference between a Python module and a Python package?