home ホーム search 検索 -  login ログイン  | reload edit datainfo version cmd icon diff delete  | help ヘルプ

Python/codepiece/プロパティ, property()

Python/codepiece/プロパティ, property()

Python / codepiece / プロパティ, property()
id: 223 所有者: msakamoto-sf    作成日: 2009-03-22 11:47:16
カテゴリ: Python 

いわゆるsetter()とgetter()を参照/代入形式で呼び出せる「プロパティ」というのが、Pythonでも2.2からサポートされています。

特に難しい概念ではないと思いますので、簡単なcodepieceで動かしてみるに留めます。

>>> class C(object):
...   def __init__(self): self.__x = 0
...   def getx(self): return self.__x * 2
...   def setx(self, value): self.__x = value * 2
...   def delx(self): self.__x = None
...   x = property(getx, setx, delx, "this is property x")
...
>>> class C(object):
...   def __init__(self): self.__x = 0
...   def getx(self): return self.__x * 2
...   def setx(self, value): self.__x = value * 2
...   def delx(self): self.__x = 0
...   x = property(getx, setx, delx, "this is property x")
...
>>> c = C()
>>> c.x
0
>>> c.x = 3
>>> c.x      #... 3 x 2 x 2
12
>>> del c.x
>>> c.x
0

ところで・・・一応docstringも指定できるみたいなんだけど。

help(c.x)

ってやったらintオブジェクトのhelpが出てきちゃったし、

c.x.__doc__

もintオブジェクトの__doc__だし。
ひょっとして

c.x

の時点でintが返されるので、それで評価されちゃってる?

まぁ、実際に使う時に調べてみますか・・・。



プレーンテキスト形式でダウンロード
現在のバージョン : 1
更新者: msakamoto-sf
更新日: 2009-03-22 11:57:04
md5:cb500bf947aa162dbd229410732e123a
sha1:78e9dcc36e1376e4cc362270da644cb60b94fd46
コメント
コメントを投稿するにはログインして下さい。