开发者

Way to encapsulate instance fields in Python

Is this use of @property decorator appropriate to obtain a good encapsulation of instance fields? I'm trying to achieve that Foobar class' clients can't assign arbitrary values to the field vel of Foobar instances in any way, de facto bypassing assignment rules defined in the property setter method.

Thanks.

class Foobar(object):
    def __init__(self):
        self._vel = 0

    @property
    def vel(self):
        return self._vel

    @vel.开发者_运维技巧setter
    def vel(self, v):
        self._vel = v if v > 0 else 0

The field seems well encapsulated.

>>> foobar = Foobar()
>>> foobar.vel
0
>>> foobar.vel = -1
>>> foobar.vel
0
>>> foobar.vel = 1
>>> foobar.vel
1


You can't prevent the user from bypassing anything in python. There's always a way to monkeypatch/reflect/inspect attributes; There's no object sandboxing support.

In your example:

>>> foobar._vel = -1

Would bypass the property entirely and assign directly to the real attribute. You can't prevent it at all. There are methods to make it harder, but the user can assign if she really wants to, so what's the point?

The usual approach seems to be to rely on the fact that the users of your library are adults and trust them:

Declare the range of expected values in the documentation and ask users to follow. If they don't it's their fault.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜