2013-03-29 8 views
28

私はZed ShawのLearn Python The Hard Wayを学びます。私はレッスン26です。このレッスンではコードを修正する必要があり、コードは別のスクリプトの関数を呼び出します。彼は、テストに合格するためにそれらをインポートする必要はないと言いますが、私はそれをどうやって行うのだろうかと不思議です。Pythonスクリプトを別のものにインポートしますか?

Link to the lesson |

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) 

答えて

64

それは最初のファイル内のコードが構成されている方法によって異なります。Link to the code to correct

そしてここでは、前のスクリプトを呼び出すコードの特定の行があります。

それは同様に、機能のちょうど束だ場合:

# 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" 

注:これは、2つのファイルが同じディレクトリにあることを前提としています。

他のディレクトリやモジュール内のシンボル(関数、クラスなど)をインポートする場合は、少し複雑になります。

+0

ああ、彼らはちょうど同じディレクトリにいなければなりません...すばらしい!ありがとうございました! – astroblack

+1

これはPython 3のどのように変わるのですか? – Brian

+0

最初の方法では、どのシンボルがインポートされませんか? – Goldname

15

これは(少なくともPython 3では)これを言及する価値があります。これを機能させるには、同じディレクトリに__init__.pyという名前のファイルが必要です。

+0

それは空にできますか? – LoveMeow

+0

@LoveMeowはい、問題ありません。 http://stackoverflow.com/questions/448271/what-is-init-py-for – soungalo

+4

これは実際に私の場合ではありません。それはうまく動作しません –

関連する問題