python の @property が果たす役割
あるメソッドを、読取専用のアトリビュートにする。
class Point: def __init__(self, point_x, point_y): self._point_x = point_x self._point_y = point_y @property def point_x(self): return self._point_x @property def point_y(self): return self._point_y p = Point(10, 33) print(p.point_x) #=> 10 print(p.point_y) #=> 33
冒頭の定義に従えば、@property に使うメソッド名は変数名に寄せなくてもよい。
class Point: def __init__(self, point_x, point_y): self._point_x = point_x self._point_y = point_y @property def tell_me_the_x(self): return self._point_x @property def what_is_y(self): return self._point_y p = Point(10, 33) print(p.tell_me_the_x) #=> 10 print(p.what_is_y) #=> 33
参考記事:
__name__ == '__main__' を使う場合
from samplepackage import yourmodule
を実行したとき、yourmodule
内のコードはすべて実行される。
例えば samplepackage/yourmodule.py
が次のコードで構成されているとする。
def sample_func(): print('hello from sample func.') sample_func()
import した時点で sample_func()
も一緒に実行される。
- import した時点では
sample_func()
を呼びたくない python samplepackage/yourmodule.py
を実行した場合はsample_func()
を呼ぶ
という場合は samplepackage/yourmodule.py
は次の通りとするのが妥当である。
def sample_func(): print('hello from sample func.') if __name__ == '__main__': sample_func()
利用しないループ変数はアンダースコアにする
内包表記を使って余計な行数を減らす
data_x = [1, 2, 3] data_y = [6, 7, 8] mul_result = [x * y for x in data_x for y in data_y] print(mul_result) => [6, 7, 8, 12, 14, 16, 18, 21, 24]
names = ['taro', 'kenji', 'joe'] ages = [25, 30, 18] people = {name: age for (name, age) in zip(names, ages)} print(people) => {'taro': 25, 'kenji': 30, 'joe': 18}
ubuntu server 20.04 に pip3 と pipenv を install する
$ sudo apt update $ sudo apt install python3-pip $ pip3 --version pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8) $ cd /path/to/workspace $ pip3 install --user pipenv # ~/.bashrc か ~/.bash_profile に PATH 通して WARN ログが出ないようにする export PATH=$PATH:/home/YOUR_NAME/.local/bin $ source ~/.bashrc $ pipenv --version pipenv, version 2020.6.2
参考記事: