27
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonを必要最低限の知識で使っていたが、参考書を買って改めて勉強して新しく知ったことや便利だと思ったことをまとめる

Last updated at Posted at 2017-03-11

背景

  • 最初にPythonを触ったのは、かれこれ4年くらい前でした。(ブランクもありPython歴は2年弱くらい)
  • 当時は業務で必要に迫られ体系的に学ぶ時間もなく、引継ぎされたコードを解読するという勉強方法でした。
  • これまで必要最低限の知識でやり過ごしてきましたが、同僚がPythonを勉強始めるということで、私もこれをきっかけに勉強しようと思いました。
  • 私の無知さを晒しますが、私のようななんちゃってPython始めましたという人のお役に立てればと思いまとめます。

利用用途

  • データ加工
  • データ分析

まとめた内容(随時更新)

  • 順番などばらばらとなります。

みんなが1行目に書く例のあれ

  • 以下のどちらかをよく見かける。(私はおまじないと教わりました。w)
    • #!/usr/bin/python
    • #!/usr/bin/env python
  • これはPythonを実行するときスクリプトの前にpythonとつけなくても実行できるようにするためのコード。
  • ただしスクリプトに chmod 744 で実行権限を付与する必要がある。(所有者はすべての権限を付与し、所属グループ、その他には閲覧権限のみを付与する)
  • 意図したPythonを呼び出せているかターミナル上で /usr/bin/python/usr/bin/env python を実行してみて確認してみるといいと思う。

sys.argv[0]

  • sys.argv[0]には自身のスクリプト名が入っている。
  • 結果例を以下にて。
test.py
import sys
print(sys.argv[0])
print(sys.argv[1])
terminal
$ python test.py 1
test.py
1

$ python ./test.py 1
./test.py
1
  • スクリプト名に情報を持たせておけば、splitなりで利用できそう。
  • 無駄に引数で情報を渡す必要はなさそう

可変長引数

  • タプル型と辞書型の2種類で可変長な引数を渡せる

タプル型

>>> def taple_func(*args):
...     for i in args:
...         print(i)
... 
>>> args=(1,2,3,4)
>>> taple_func(*args)
1
2
3
4
>>> taple_func(1,2,3,4)
1
2
3
4

辞書型

>>> def dict_func(**kwds):
...     for i in kwds:
...         print(i)
... 
>>> kwds={'a':1, 'b':2, 'c':3, 'd':4}
>>> dict_func(**kwds)
b
d
a
c
>>> dict_func(a=1, b=2, c=3, d=4)
b
d
a
c

デコレータ

  • 関数を修飾という仕組み。
>>> def decorator_a(seq_id):
...     def _decorator_a(func):
...         import functools
...         @functools.wraps(func)
...         def __decorator_a(*args,**kwargs):
...             res = '<' + seq_id + '>'
...             res = res + func(*args,**kwargs)
...             res = res + '<' + seq_id + '>'
...             return res
...         return __decorator_a
...     return _decorator_a
... 
>>> @decorator_a('A')
... @decorator_a('B')
... def test():
...     return 'decorator test'
... 
>>> print(test())
<A><B>decorator test<B><A>
  • 仕組みは理解できたが活用場面がいまいちわからない

assert

記述法

assert 条件式, メッセージ

※メッセージは省略可能

説明

  • 条件式が成立しない場合プログラムを強制終了する。
  • プログラムのテストやデバッグ時に便利。

raise

記述法

raise エラークラス(メッセージ)

説明

  • エラーを故意に発生させる。
  • プログラムのテストやデバッグ時に便利。

with

記述法

with open('test,tsv', 'r') as f:
    print(f.write('test'))

説明

  • withステートメントを抜けると自動的にf.colse()をしてくれる。
  • コードの可読性が上がる。

参考

27
35
4

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
27
35

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?