1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonのimport文は、他のモジュールやパッケージから関数、クラス、変数などを取り込み、再利用するための機能です。asを使うと、インポートするモジュールや関数に別名(エイリアス)を付けることができます。これにより、名前を短くしたり、同じ名前の衝突を避けたりすることができます。

基本的なimportの使い方

モジュール全体のインポート
特定のモジュール全体をインポートする場合、次のように記述します。

import モジュール名

例: mathモジュールをインポートして数学関数を利用する場合

import math

print("Square root of 16 is", math.sqrt(16))
print("Value of pi is", math.pi)

from を使ったインポート
モジュール全体ではなく、特定の関数やクラスだけをインポートする場合、fromを使います。

from モジュール名 import 関数名, クラス名

例: mathモジュールから特定の関数だけをインポート

from math import sqrt, pi

print("Square root of 25 is", sqrt(25))
print("Value of pi is", pi)

as を使ったエイリアス
モジュールや関数に別名を付けるためにasを使います。名前が長い場合や、名前の衝突を避ける場合に便利です。

コードをコピーする
import モジュール名 as 別名

例: numpyモジュールをエイリアスnpとしてインポート

import numpy as np

array = np.array([1, 2, 3])
print("NumPy array:", array)

例: 関数に別名を付けてインポート

from math import sqrt as square_root

print("Square root of 49 is", square_root(49))

組み合わせた使い方

モジュール全体をエイリアス付きでインポート

import matplotlib.pyplot as plt

# プロットを作成
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

説明: matplotlib.pyplotpltという短い名前でインポートして、プロットを作成しています。

特定の関数をエイリアス付きでインポート

from datetime import datetime as dt

# 現在の日時を取得
now = dt.now()
print("Current date and time:", now)

説明: datetimeモジュールからdatetimeクラスをdtという名前でインポートし、現在の日時を取得しています。

import * について

from モジュール名 import * を使うと、モジュール内のすべての内容をインポートできますが、名前の衝突が発生しやすくなるため、あまり推奨されません。

from math import *

print("Cosine of 0 is", cos(0))

注意: *でインポートすると、どの名前がどのモジュールから来ているのかが不明瞭になるため、可読性が低下します。

実際の使用例
次に、いくつかの実際の使用例を示します。

例1: ファイルの読み書きに使うosモジュール

import os

# 現在のディレクトリを取得
current_directory = os.getcwd()
print("Current directory:", current_directory)

例2: JSONの読み書きに使うjsonモジュール

import json

# PythonオブジェクトをJSON文字列に変換
data = {"name": "Alice", "age": 25}
json_string = json.dumps(data)
print("JSON string:", json_string)

# JSON文字列をPythonオブジェクトに変換
parsed_data = json.loads(json_string)
print("Parsed data:", parsed_data)

例3: randomモジュールでランダムな数を生成

import random

# 1から10までのランダムな整数を生成
random_number = random.randint(1, 10)
print("Random number between 1 and 10:", random_number)

参考) 東京工業大学情報理工学院 Python早見表

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?