Python でプロパティ機能を使用する方法に関する実際の例はありますか? 質問する

Python でプロパティ機能を使用する方法に関する実際の例はありますか? 質問する

Python での使用方法に興味があります@property。Python のドキュメントを読みましたが、そこにある例は、私の意見では単なるおもちゃのコードです。

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

_xfilled をプロパティ デコレータでラップすることでどのような利点が得られるかわかりません。次のように実装してはいかがでしょうか。

class C(object):
    def __init__(self):
        self.x = None

プロパティ機能は、状況によっては役立つかもしれないと思います。しかし、いつ役立つのでしょうか? 誰か実際の例をいくつか教えていただけませんか?

ベストアンサー1

その他の例としては、設定された属性の検証/フィルタリング(境界内または許容範囲内に強制する)や、複雑な用語や急速に変化する用語の遅延評価などが挙げられます。

属性の背後に隠された複雑な計算:

class PDB_Calculator(object):
    ...
    @property
    def protein_folding_angle(self):
        # number crunching, remote server calls, etc
        # all results in an angle set in 'some_angle'
        # It could also reference a cache, remote or otherwise,
        # that holds the latest value for this angle
        return some_angle

>>> f = PDB_Calculator()
>>> angle = f.protein_folding_angle
>>> angle
44.33276

検証:

class Pedometer(object)
    ...
    @property
    def stride_length(self):
        return self._stride_length

    @stride_length.setter
    def stride_length(self, value):
        if value > 10:
            raise ValueError("This pedometer is based on the human stride - a stride length above 10m is not supported")
        else:
            self._stride_length = value

おすすめ記事