LoginSignup
99
100

More than 5 years have passed since last update.

Pythonで簡単に自作関数を使いまわす

Last updated at Posted at 2015-02-16

まず自作関数を作ります.

myplot.py
import matplotlib.pyplot as plt

def myplot(x):
    plt.plot(x, 'o-')
    plt.show()

if __name__ == '__main__':
    x = [i**2 for i in range(20)]
    myplot(x)

ここでファイル名と関数名を同じにするのが好きです.

figure_1.png

これを自作の関数集フォルダに入れておきます.

mymodule/
  __init__.py
  myplot.py

中にこのファイルをおいておけば,

__init__.py
from myplot import myplot

mymodule からストレスなく myplot をインポートできます.

test_myplot.py
from mymodule import myplot

x = [(-0.5)**i for i in range(20)]
myplot(x)

figure_1.png

ただしこの場合,実行した test_myplot.py は mymodule と同じフォルダにある必要があります.

mymodule
test_myplot.py

そこで,自作関数集を特定のフォルダに集めておきます.

/home/okadate/pyfiles/
  mymodule
  mymodule2

自由な位置にある test_myplot.py をこうしておけば,

test_myplot.py
import sys; sys.path.append('/home/okadate/pyfiles')
from mymodule import myplot

x = [i/(5.0+i) for i in range(30)]
myplot(x)

figure_1.png

使えます!

他にもパッケージ化してしまうなどの方法があるみたいです.
簡単ならやってみたいけど..

99
100
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
99
100