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

Python - モジュール、パッケージ、名前空間パッケージの概要

次の記事 >

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

Python

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

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

1. 概要

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

2. モジュールのインポート

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

calc.py をインポートします。モジュールで定義された関数などを使う時は、「モジュール名.関数」のように、先頭にモジュール名を付けます。

test.py
import calc

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

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

def mul(v1, v2):
	return v1 * v2

実行結果
3
12

また、以下のようにしてインポートすると、モジュール名を省略して、モジュールの関数を使用できます。

test.py
from calc import add
from calc import mul

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

インポートする関数を1行にまとめることもできます。
from calc import add, mul

import * で、全てのメンバをインポートすることもできます。
但し、先頭が _(アンダースコア)のメンバはインストールされません。
from calc import *

既存の関数などと重複する場合は、as で別名を付けてインポートすることもできます。
from calc import add as calc_add
from calc import mul as calc_mul

print( calc_add(1, 2) )
print( calc_mul(3, 4) )


< 前の記事

Python - モジュール、パッケージ、名前空間パッケージの概要

次の記事 >

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.

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