Python封装实例字段的方法
使用 @property 装饰器 是否适合获得实例字段的良好封装?我试图实现 Foobar 类的客户端无法以任何方式向 Foobar 实例的字段 vel
分配任意值,事实上绕过了属性设置方法中定义的分配规则。
谢谢。
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
该领域似乎封装得很好。
>>> foobar = Foobar()
>>> foobar.vel
0
>>> foobar.vel = -1
>>> foobar.vel
0
>>> foobar.vel = 1
>>> foobar.vel
1
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你无法阻止用户绕过 python 中的任何内容。总有一种方法可以对属性进行猴子修补/反射/检查;没有对象沙箱支持。
在您的示例中:
将完全绕过该属性并直接分配给真实属性。你根本无法阻止它。有一些方法可以让它变得更难,但是用户可以根据自己的需要进行分配,那么这有什么意义呢?
通常的方法似乎是依赖于您的图书馆的用户是成年人并信任他们的事实:
在文档中声明预期值的范围并要求用户遵循。如果他们不这样做,那是他们的错。
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:
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.