将Python脚本导入另一个? [英] Import Python Script Into Another?

查看:258
本文介绍了将Python脚本导入另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Zed Shaw的学习Python的艰难之路,我正在上第26课。在本课中,我们必须修复一些代码,代码从另一个脚本调用函数。他说我们不必导入它们来通过测试,但我很好奇我们将如何这样做。

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.

链接到课程 | 链接到要更正的代码

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

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"

# second.py
from first import foo, bar

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

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

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脚本导入另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆