home Glamenv-Septzen(ぐらめぬ・ぜぷつぇん)(archive)

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

作成日: 2009-03-22 11:47:16   /   last updated at: 2009-03-22 11:57:04
カテゴリ: 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が返されるので、それで評価されちゃってる?

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


original url: https://www.glamenv-septzen.net/view/223