インポートとは?
状態:-
閲覧数:1,305
投稿日:2018-02-15
更新日:2018-03-15
読込
モジュールあるいはパッケージを読み込み、利用可能にすること
・Pythonでは同じパッケージ内でモジュールが異なればインポートが必要
・複数指定可能
モジュールのインポートには import 文を使用
インポート対象
・クラス名や関数名を指定
モジュールをインポート
インポート実行
作成したモジュール
・他のモジュールからimportを使ってインポートすることが出来る
import モジュール名
具体例
・a.pyをインポート
・拡張子の.pyは不要
import a # モジュールをインポート
インポート後
クラスを使う場合
・モジュール名を先頭に付けクラス名をドットでつなげる
モジュール名.クラス名
メソッドを使う場合
・モジュール名を先頭に付けメソッド名をドットでつなげる
モジュール名.メソッド名
.変数を使う場合
・モジュール名を先頭に付け.変数名をドットでつなげる
モジュール名..変数名
具体例
▼greeting_module.py
class GreetingClass:
def sayStr(self, str):
print str
▼index.py
import greeting_module # モジュールをインポート
greeting = greeting_module.GreetingClass()
greeting.sayStr("Hello") # Hello
・__main__ — トップレベルのスクリプト環境
・モジュール (module)
fromを使ってインポート
fromを使ってインポート実行
クラスを作る度にモジュール名を記述するのが面倒だという場合、fromを使用
from モジュール名 import クラス名
fromを使ってインポートすると?
インポート後に呼び出す際、モジュール名を記述する必要がなくなる
・クラスを直接呼び出すことができる
具体例
▼greeting_module.py
class GreetingClass:
def sayStr(self, str):
print str
▼index.py
from greeting_module import GreetingClass
greeting = GreetingClass()
greeting.sayStr("Hello") # Hello
asを使って別名でインポート
モジュールを別名でインポートするにはasを使用
import モジュール名 as 別名
具体例
▼greeting_module.py
class GreetingClass:
def sayStr(self, str):
print str
▼index.py
import greeting_module as g # gという別名でgreeting_moduleをインポート
greeting = g.GreetingClass()
greeting.sayStr("Hello") # Hello
Pythonでモジュールをインポートする:import, from, as | UX MILK
6. モジュール (module) — Python 3.6.3 ドキュメント
モジュールのインポート方法いろいろ — Python School 2.0.0 documentation
import の使い方 - Life with Python
Pythonで標準ライブラリのモジュールをインポートして使ってみよう
Python/モジュールのインポート - Wikibooks
効率よく開発できる!Pythonでimportを使う方法 | TechAcademyマガジン