2

a.py次のようなpythonファイルを作成しました。

x = 1
def hello():
   print x

hello()

私がするときimport a、それはの値を印刷していますx

これまでの私の理解でimportは、変数と関数の定義が含まれますが、なぜメソッドを実行しているのhello()でしょうか?

4

4 に答える 4

6

Python imports are not trivial, but in short, when a module gets imported, it is executed top to bottom. Since there is a call to hello, it will call the function and print hello.

For a deeper dive into imports, see:

To be able to use a file both standalone and as a module, you can check for __name__, which is set to __main__, when the program runs standalone:

if __name__ == '__main__':
    hello()

See also: What does if __name__ == "__main__": do?

于 2013-09-06T08:16:21.757 に答える
4

Python では、宣言と実行の間に明確な分離はありません。実際には、実行ステートメントしかありません。たとえばdef hello():...、モジュール変数に関数値を代入する方法にすぎませんhello。モジュールがインポートされると、モジュール内のすべてのステートメントが順番に実行されます。

そのため、彼らはしばしば次のようなガードを使用します。

if __name__=='__main__':
   # call hello() only when the module is run as "python module.py"
   hello()
于 2013-09-06T08:20:01.157 に答える
1

一番下で hello() 関数を呼び出したので、「import a」を実行するとその関数が実行されます。

于 2013-09-06T08:17:38.107 に答える
0

最後にを削除する必要がありhello()ます。これが関数を実行しているものです。ファイル内の宣言のみが必要ですa.py

于 2013-09-06T08:18:21.750 に答える