LoginSignup
3
1

More than 5 years have passed since last update.

実践Python3でやってた簡単なシングルトン

Last updated at Posted at 2018-03-10

コード

スイッチモジュール

switch.py
def push():
    push.state = not push.state
    return push.state


push.state = False

使う側

In [1]: import switch

In [2]: switch.push()
Out[2]: True

In [3]: switch.push()
Out[3]: False

In [4]: switch.push()
Out[4]: True

やったこと

  • グローバルな状態を持つモジュールswitch.pyを作成する
  • そのモジュールにプライベートな変数を保持させ,変数へのアクセスはパブリックな関数push()で行わせる

これによりプログラムでただ1つの状態を持つグローバルなスイッチができる.実践Python3ではネットから通貨レートの情報をとってきて保持するために使っている.通貨レートを取得する関数は数回呼ばれるが,ネットから取得するのは一回で良いのでこの実装を用いている.

3
1
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
3
1