Python property() 関数

Python 内置函数Python 組み込み関数


説明

property()この関数は、新スタイルクラスで属性値を返す働きをします。

構文

以下は property() メソッドの構文です:

class property([fget[, fset[, fdel[, doc]]]])

パラメータ

  • fget -- 属性値を取得する関数
  • fset -- 属性値を設定する関数
  • fdel -- 属性値を削除する関数
  • doc -- 属性の説明情報

戻り値

新スタイルクラスの属性を返します。

例

制御可能な属性値 x を定義する

class C(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.")

もしcであるCc をインスタンス化すると、c.x は getter をトリガーし、c.x = value は setter をトリガーし、del c.x は deleter をトリガーします。

doc パラメータが与えられた場合、それがこの属性値の docstring になります。それ以外の場合、property 関数は fget 関数の docstring(もしあれば)をコピーします。

property 関数をデコレータとして使うと、読み取り専用属性を簡単に作成できます:

class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage

上記のコードは、voltage() メソッドを同名の読み取り専用属性の getter メソッドに変換します。

property の getter、setter、deleter メソッドも同様にデコレータとして使用できます:

class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x

このコードは最初の例と完全に同じですが、これらの追加関数の名前が property の下のものと同じであることに注意してください。例えば、ここでの x です。

Python 内置函数Python 組み込み関数

その他の拡張