Python デザインパターン サンプルコード Singleton
Mark Summerfield『実践 Python 3』デザインパターンのサンプルコード
Python3(3.11)で動くソースコード(.pyファイル .ipynbファイル)あります
「anaconda3」on .py「PyCharm」.ipynb「Jupyter Notebook」
(2023-11-16)Python3.11で動作確認済み
【重要な注意】ソースコードの16行目にあるURLはブラウザに貼り付けつけるだけでファイルのダウンロードができます(再現性あり)。本プログラムは,そのファイルを1回だけダウンロードできるというシングルトンまがいのプログラムです。
ただ,デバッグでは確かに1回だけはダウンロードできたのだが,その後はダウンロードを再現するのに苦労しました。
本来のシングルトンはクラスのインスタンスオブジェクトを1つしかつくることのできないプログラムです。本プログラムはグローバル関数で疑似的に実現しています。本来のシングルトンは次を参照してください。
結城 浩「Java言語で学ぶデザインパターン入門」をPython化
https://yamakatsusan.web.fc2.com/pythonpattern05.html
『Python デザインパターン サンプルコード Singleton』
クラスはありません グローバル関数が1つあるだけですSingleton パターンの本来の目的は,1つのクラスを複数回インスタンス化しても1つのインスタンスしかできない特殊なクラスを提供することにある。しかし,サンプルはそうではない。
39 40 41 42 43 44 45
if __name__ == "__main__": import sys if sys.stdout.isatty(): print(get()) else: print("Loaded OK") print(get())
Date,FXAUDCAD,FXBRLCAD,FXCNYCAD,FXEURCAD,FXHKDCAD,FXINRCAD 2017/1/3,0.9702,0.4121,0.193,1.3973,0.173212,0.01965 2017/1/4,0.9678,0.4129,0.192,1.393,0.171687,0.01959 2017/1/5,0.9708,0.4133,0.1922,1.4008,0.170792,0.01954 2017/1/6,0.9668,0.4116,0.1911,1.3953,0.170556,0.01942 2017/1/9,0.9728,0.4135,0.1907,1.3967,0.170572,0.01942
{'2017/1/3 (0.9702)': 0.01965, '2017/1/4 (0.9678)': 0.01959, '2017/1/5 (0.9708)': 0.01954, '2017/1/6 (0.9668)': 0.01942, '2017/1/9 (0.9728)': 0.01942}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#!/usr/bin/env python3 # Copyright c 2012-13 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. It is provided for # educational purposes and is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. import re import urllib.request _URL = "https://yamakatsusan.web.fc2.com/FX_RATES.csv" def get(refresh=False): if refresh: get.rates = {} if get.rates: return get.rates with urllib.request.urlopen(_URL) as file: for line in file: line = line.rstrip().decode("utf-8") if not line or line.startswith(("#", "Date")): continue name, currency, *rest = re.split(r"\s*,\s*", line) key = "{} ({})".format(name, currency) try: get.rates[key] = float(rest[-1]) except ValueError as err: print("error {}: {}".format(err, line)) return get.rates get.rates = {} if __name__ == "__main__": import sys if sys.stdout.isatty(): print(get()) else: print("Loaded OK") # print(get()) # 故意にエラー?