LoginSignup
1
2

More than 3 years have passed since last update.

【Pythonista3を使ったみた】自作モジュールのインポート

Last updated at Posted at 2020-05-07

モジュールって?

モジュールとは、Pythonの定義や文が入ったファイルのことです。
(ファイル名の接尾語に.pyがついたものです)
以下のファイルもモジュールとして扱えます。

HelloWorld.py
print( HelloWorld )

インポートって?

例として標準ライブラリのosモジュールをインポートする。

import_test.py
import os
print( type( os ) )
# <class ‘module’>
print( os.getcwd() )
# /private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/Test

以上のようにimport <モジュール名>とするとインポートできます。
モジュールはmodule型のオブジェクトとしてインポートされます。

自作モジュールのインポート

ディレクトリ

  • iCould
    • Test
      • MyFunc
        • MyCalc.py
      • MyCalcTest.py

以上のようなディレクトリで進めていきます。
MyCalcTest.pyMyCalc.pyモジュールをインポートして
MyCalc.pyモジュールの関数を使ってみます。

MyCalc.py
'''
自作計算モジュール
'''
def sum ( v1, v2 ) :
    '''
    加算
    '''
    return v1 + v2

def sub ( v1, v2 ) :
    '''
    減算
    '''
    return v1 - v2
MyCalcTest.py
import MyFunc.MyCalc

v1 = 10
v2 = 5

res1 = MyFunc.MyCalc.add( v1, v2 )
print( "%d + %d = %d" %( v1, v2, res1 ) )
#>> 10 + 5 = 15

res2 = MyFunc.MyCalc.sub( v1, v2 )
print( "%d - %d = %d" %( v1, v2, res2 ) )
# 10 - 5 = 5

こんな感じでMyCalc.pyモジュールの関数が使えました。

自作モジュール内に関数の簡易アクセス

MyFunc.MyCalc.addとか毎回書くの面倒ですよねー。

オブジェクトをインポート

オブジェクト指定

from <モジュール名> import <オブジェクト名>でオブジェクトをインポートできます。

import_test.py
from MyFunc.MyCalc import add, sub

v1 = 10
v2 = 5

res1 = add( v1, v2 )
print( "%d + %d = %d" %( v1, v2, res1 ) )

res2 = sub( v1, v2 )
print( "%d - %d = %d" %( v1, v2, res2 ) )

すべてのオブジェクト

ワイルドカード*を使うことですべてのオブジェクトがインポートできます。

import_test.py
from MyFunc.MyCalc import *

v1 = 10
v2 = 5

res1 = add( v1, v2 )
print( "%d + %d = %d" %( v1, v2, res1 ) )

res2 = sub( v1, v2 )
print( "%d - %d = %d" %( v1, v2, res2 ) )

結論

ディレクトリ階層によってはインポートするパス名が長くなるので
そのまま使うのではなく、オブジェクト指定する方が良い。
ワイルドカードはとても楽に使えるのが名前空間に存在しているか
不明なため控えるようがいいかも。

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