言語仕様¶
はじめに¶
基本的にPython3の仕様のみを書く。
ただし、ぐぐった結果とかを貼っているものはPython2のことがあるかもしれない。
ドキュメント:
import¶
リファレンス:
import文¶
https://docs.python.org/ja/3/reference/simple_stmts.html#import
例:
参考:
モジュール検索パス¶
https://docs.python.org/ja/3/tutorial/modules.html#the-module-search-path
sys.path のリストから探す。sys.path は以下で初期化される:
- カレントディレクトリ(あるいは入力されたスクリプトのあるディレクトリ)
- 環境変数 PYTHONPATH
- インストールごとのデフォルト
参考:
コメント¶
複数行のコメントは """ または ''' で書く。
参考:
リテラル¶
https://docs.python.org/ja/3/reference/lexical_analysis.html#literals
文字列¶
Examples:
See also:
参考:
演算子¶
二項演算子¶
6. 式 (expression) — Python 3 ドキュメント
@... 行列の乗算
累算代入演算子¶
https://docs.python.org/ja/3/reference/simple_stmts.html#augmented-assignment-statements
Examples:
NOTE:
- Rubyの
||=相当はない
三項演算子¶
Syntax:
Example:
参考:
*, ** 展開¶
- リストやタプルには
*、dictには**を付けることで展開して、関数の引数にすることができる。
参考:
制御構文¶
条件分岐¶
https://docs.python.org/ja/3/tutorial/controlflow.html#if-statements
参考:
ループ¶
参考:
関数¶
return¶
https://docs.python.org/ja/3/reference/simple_stmts.html#the-return-statement
構文:
NOTE:
- 多値を返すこともできる
Examples:
参考:
decorator (デコレータ)¶
https://docs.python.org/ja/3/reference/compound_stmts.html#function-definitions
ある関数に対して、前処理や後処理などを追加したりできるシンタックスシュガー。
例:
@f1 や @f2 がデコレータであり、 func() に対してネストして適用される。
上のコードはだいたい次と等価:
参考:
関連項目
クラス¶
https://docs.python.org/ja/3/tutorial/classes.html
例外処理¶
https://docs.python.jp/3/tutorial/errors.html
Examples:
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except IOError as err:
# 例外の連鎖/変換
raise RuntimeError('Failed to open or read file!') from err
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
else:
print("No error.")
finally:
f.close()
参考:
書式付き文字列¶
参考:
ジェネレータ¶
反復可能なオブジェクト
- ジェネレータ関数 ...
yieldを使う - ジェネレータ式
参考:
組み込み関数¶
https://docs.python.jp/3/library/functions.html
list()¶
https://docs.python.jp/3/library/functions.html#func-list
Example:
参考:
トピック¶
アンダースコア(_)¶
_ の使い方:
- 返り値を無視する
- 関数や変数の役割を変える
- 数字を読みやすくする
Examples:
a, _, c = (1, 2, 3)
# 先頭に1つの「_」で規約としてプライベート化する
# 「weak internal use」と呼ばれる
_foo = 'foo'
def _bar():
return 'bar'
class Sample:
# 普通のメソッドとして呼べなくなる
# 疑似private関数
def __foo():
return 'foo'
n = 1_000_000 # 1000000 と同じ
参考: