5
6

More than 3 years have passed since last update.

Python、fromとimport、asについて

Last updated at Posted at 2020-03-12

pythonで使用するfromとimportの違いをメモ(例としてtoday関数を使い、2通りの方法を記述)

(1)datetimeモジュール(ファイル)をインポートするのみ

datetimeモジュールの、datetimeクラスのtoday関数を使う、という記述をする

import datetime
datetime.datetime.today()

結果として

datetime.datetime(2020, 3, 12, 23, 21, 41, 756354)

となる。

(2)datetimeモジュール(ファイル)とdatetiemクラスをインポートする

上記の例ではモジュール名.クラス名とするのが面倒です。そんなときはimportだけでなくfromも使ってインポートします。
from モジュール名 import クラス名(もしくは関数名や変数名)
datetimeクラスのtoday関数を使う、という記述をする

from datetime import datetime
datetiem.today()

結果は同様に

datetime.datetime(2020, 3, 12, 23, 21, 41, 756354)

となる。

(3)おまけ

asを使うとライブラリ名(モジュール名)を好きな言葉で使うことができる。

import datetime as t
t.datetime.today()

結果は同様に

datetime.datetime(2020, 3, 12, 23, 21, 41, 756354)

となる。

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6