« 日記 |Main| 日記 »

« 一連の関数のリストを作る | Python | Pythonのジェネレータで四角いらせんを書いた »

Pythonのジェネレータを使ってprivateな変数

Pythonのジェネレータを使えば変数の値を隠せるんじゃないかとふと思ったのだけどダメだったという話。 下のようなコードならprivateな値にアクセスする方法がないんじゃないかと期待した。
>>> def Counter():
	private = {"count": 0} # private
	def push():
		private["count"] += 1
		print private["count"], "回押されました"
	def clear():
		private["count"] = 0
	public = {"push": push, "clear": clear}
	yield public

>>> c = Counter()
>>> c.next()
{'push': <function push at 0x00E3D1B0>, 'clear': <function clear at 0x00E3D370>}
>>> push = _["push"]
>>> push()
1 回押されました
>>> push()
2 回押されました
>>> push()
3 回押されました
でもdirしてみたらフレームの情報があるのが見えてしまったのですぐにprivateな値に到達。
>>> c.gi_frame.f_locals["private"]
{'count': 3}

トラックバック(Trackback)

Trackback URL: http://www.nishiohirokazu.org/mt/mt-tb.cgi/397

ご意見・ご感想をお送りください(フィードバック)

(フィードバックはメールで送信され、基本的に表示されませんが、内容によっては公開させていただくこともございます。ご了承ください。Your comment doesn't appear the page immediately. If the comment has value to other people, it will be put on the page or subsequent entries. Thank you.)

上の情報は、いずれも未記入でかまいません。 All of above questions are optional.