a.py
次のようなpythonファイルを作成しました。
x = 1
def hello():
print x
hello()
私がするときimport a
、それはの値を印刷していますx
これまでの私の理解でimport
は、変数と関数の定義が含まれますが、なぜメソッドを実行しているのhello()
でしょうか?
a.py
次のようなpythonファイルを作成しました。
x = 1
def hello():
print x
hello()
私がするときimport a
、それはの値を印刷していますx
これまでの私の理解でimport
は、変数と関数の定義が含まれますが、なぜメソッドを実行しているのhello()
でしょうか?
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?
Python では、宣言と実行の間に明確な分離はありません。実際には、実行ステートメントしかありません。たとえばdef hello():...
、モジュール変数に関数値を代入する方法にすぎませんhello
。モジュールがインポートされると、モジュール内のすべてのステートメントが順番に実行されます。
そのため、彼らはしばしば次のようなガードを使用します。
if __name__=='__main__':
# call hello() only when the module is run as "python module.py"
hello()
一番下で hello() 関数を呼び出したので、「import a」を実行するとその関数が実行されます。
最後にを削除する必要がありhello()
ます。これが関数を実行しているものです。ファイル内の宣言のみが必要ですa.py