9cubed
ブログ | Tailwind | Vite | Python | MariaDB | Node.js | Linux | PowerShell | Docker | Git | その他 | 将棋ウォーズ | 歌の練習
< 前の記事

Python - モジュールのインポート(import)

次の記事 >

Python - 名前空間パッケージのインポート(import)

Python

Python - パッケージのインポート(import)

公開日:2019-03-08
更新日:2019-11-14

1. 概要

パッケージのモジュールをインポート(import)します。

2. 動画



3. パッケージにあるモジュールのインポート

フォルダ構成
├─ test.py (メイン)
├─ calc    (パッケージ)
├─ mod1.py (モジュール)
└─ mod2.py (モジュール)

mod1.py
def add(v1, v2):
	return v1 + v2

mod2.py
def mul(v1, v2):
	return v1 * v2

「from パッケージ名 import モジュール名」でインポートします。

test.py
from calc import mod1
from calc import mod2

print( mod1.add(1, 2) )
print( mod2.mul(3, 4) )


また、以下のようにしてインポートすることもできます。
from calc.mod1 import add
from calc.mod2 import mul

print( add(1, 2) )
print( mul(3, 4) )

import calc.mod1
import calc.mod2

print( calc.mod1.add(1, 2) )
print( calc.mod2.mul(3, 4) )

import calc.mod1 as mod1
import calc.mod2 as mod2

print( mod1.add(1, 2) )
print( mod2.mul(3, 4) )

4.1 パッケージのインポート その1

__init__.py を使うと、パッケージから参照できるメンバーを指定できます。
また、__init__.py は、パッケージのインポート時に通常のスクリプトとして実行されます。
初期化処理やインポートするモジュールを動的に変更することもできます。

├─ test.py (メイン)
├─ calc    (パッケージ)
├─ __init__.py
├─ mod1.py (モジュール:add()関数を定義)
└─ mod2.py (モジュール:mul()関数を定義)

calc の __init__.py でインポートして、関数が calc の直下にあるようにみせます。

__init__.py
from calc.mod1 import add
from calc.mod2 import mul

test.py
import calc

print( calc.add(1, 2) )
print( calc.mul(3, 4) )

4.2 パッケージのインポート その2

__init__.py で、__all__ でモジュールを指定すると、import * により、まとめてインポートすることができます。

├─ test.py (メイン)
├─ calc    (パッケージ)
├─ __init__.py
├─ mod1.py (モジュール:add()関数を定義)
└─ mod2.py (モジュール:mul()関数を定義)

__init__.py
__all__ = ["mod1", "mod2"]

test.py
from calc import *

print( mod1.add(1, 2) )
print( mod2.mul(3, 4) )


< 前の記事

Python - モジュールのインポート(import)

次の記事 >

Python - 名前空間パッケージのインポート(import)

YouTube X

新着一覧

  • テーブル結合(CROSS JOIN、INNER JOIN、LEFT JOIN)MariaDB
  • 楽観ロック・悲観ロックMariaDB
  • カレントリードMariaDB
  • インデックスMariaDB
  • 論理削除(ソフトデリート)MariaDB
  • awk(オーク)の使い方についてLinux
  • NOT NULL 制約と NULL を許容した時の動作MariaDB
  • 外部キー制約MariaDB
  • MySQL と MariaDB の関係MariaDB
  • Docker で PostgreSQL のコンテナの使用Linux

アーカイブ

  • 2026/01
  • 2025/12
  • 2025/11
  • 2025/10
  • 2025/09
  • 2025/08
  • /00

以前のカテゴリー一覧

  • CakePHP3
  • CentOS7
  • HTML・CSS・JavaScript
  • Haskell
  • JavaScript
  • Kotlin
  • Laravel5
  • PHP
  • Python
  • Ruby
  • RubyOnRails5
  • TypeScript
  • Vue.js
  • Webサーバ講座
  • Webプログラミング講座
  • jQuery
  • linux
  • パソコン講座
  • ブログ
  • プログラミング講座
  • メモ帳作成講座
  • 数学

Copyright © 9cubed. All Rights Reserved.

プライバシーポリシー 利用規約
▲