メインコンテンツまでスキップ

インポートとは?

Python のプログラムを見ているとほぼ必ず出て切るimport

import pygame
import requests

import ...

これはなんだろう?

どういうもの?

importは Python で外部のモジュールやライブラリをプログラムで使えるようにするための機能

目的

  • コードの再利用性を高める
  • 機能をモジュール化して整理する
  • 外部ライブラリの機能を使用する
import math  # 数学関数を使用する
import random # 乱数生成機能を使用する
import datetime # 日付・時間の処理を行う

インポートの種類

モジュール全体のインポート

import モジュール名

モジュールの特定の機能だけをインポート

from モジュール名 import 機能名

モジュールに別名をつけてインポート

import モジュール名 as 別名

モジュールの機能をまとめてインポート

from モジュール名 import *

まとめ

importを使用することで他の開発者が作成した便利な機能などを簡単に利用することができる。

これにより位置からすべての機能を実装しなくてもよくなる。

importがないと?

mathモジュールが必要な場合

math モジュールは数学関数を提供する。

importを使用できる場合

import math

class Calculator:
def __init__(self):
self.result = 0

def calculate(self, a, b, operation):
if operation == '+':
return a + b
elif operation == '-':
return a - b
elif operation == '*':
return a * b
elif operation == '/':
return a / b
elif operation == 'sqrt':
return math.sqrt(a)
else:
return "無効な演算です"

# 使用例
calc = Calculator()
print(calc.calculate(16, 4, '+')) # 20
print(calc.calculate(16, 4, '-')) # 12
print(calc.calculate(16, 4, '*')) # 64
print(calc.calculate(16, 4, '/')) # 4.0
print(calc.calculate(16, 0, 'sqrt')) # 4.0

importが使用できない場合

class Calculator:
def __init__(self):
self.result = 0

def calculate(self, a, b, operation):
if operation == '+':
return a + b
elif operation == '-':
return a - b
elif operation == '*':
return a * b
elif operation == '/':
return a / b
elif operation == 'sqrt':
return self._calculate_sqrt(a)
else:
return "無効な演算です"

def _calculate_sqrt(self, number):
# ニュートン法による平方根の計算
if number < 0:
return "無効な入力です"
if number == 0:
return 0

# 初期値の設定
x = number / 2

# ニュートン法による近似計算
for _ in range(10): # 10回の反復で十分な精度が得られる
x = (x + number / x) / 2

return x

# 使用例
calc = Calculator()
print(calc.calculate(16, 4, '+')) # 20
print(calc.calculate(16, 4, '-')) # 12
print(calc.calculate(16, 4, '*')) # 64
print(calc.calculate(16, 4, '/')) # 4.0
print(calc.calculate(16, 0, 'sqrt')) # 4.0

import を使用しないと一から全てを実装する必要がある。