properties - Way to encapsulate instance fields in Python -


What is the appropriate area to get good encapsulation of area? I am trying to achieve that the FOB Class Client can not by any means assign the FOBR ​​field vel to the arbitrary value, the actual bypassing assignment rule defined in the property setter method.

Thank you.

  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 & gt; 0 and 0   

The area is well explained.

  gt; & Gt; Phobor = FuBar ()> gt; & Gt; & Gt; Foobar.vel 0 & gt; & Gt; & Gt; Foobar.vel = -1 & gt; & Gt; & Gt; Foobar.vel 0 & gt; & Gt; & Gt; Foobar.vel = 1 & gt; & Gt; & Gt; Foobar.vel 1   

You can not stop the user from bypassing anything in the python Always port patch / mirrored There is a way to inspect / properties; No object sandboxing support is supported.

In your example:

  & gt; & Gt; & Gt; Foobar._vel = -1   

will completely bypass the property and assign the actual attribute directly. You can not stop it at all There are ways to make it hard, but if he really wants, then the user can specify it, so what's the matter?

The general approach depends on the fact that users of your library are adult and rely on them:

Announce the category of expected values ​​in the documentation and follow the users Ask for. If they do not make their mistake.

Comments