Python has a "really hidden encapsulation"?

Carl Banks pavlovevidence at gmail.com
Thu Oct 21 14:42:41 EDT 2010


On Oct 21, 9:49 am, dmytro starosud <d.staro... at gmail.com> wrote:
> Hello,
> I'm Python beginner (from Ukraine).
> I may have found the way to really hide attributes in Python class.
> The whole control on this attribute is implemented inside of the
> class.
> *(code is below, Python 3)
> You see that we can't get the reference to instance of class
> "en_property" outside the class "segment", but in the inside we can.
>
> *It seems like there is no way to get the reference to field
> “en_property.v_min” or “en_property.v_max”.
> And object “s” has “two” attributes “v_min”: “s.__dict__['v_min']” and
> “s.v_min”.
>
> Help me find the answer, Can I change this hidden attribute outside
> the class?
> Or is it just an interesting feature?
> ...and Python has a "really hidden encapsulation"?
[snip example]


Well, you say you can access the attribute from inside the class, but
you didn't show any examples of it.  What would happen if you had a
method that tried to run this: "self.v_min = 2"?  I didn't check it
but it looks like it'd raise the exception, too.

This is what the term "data hiding" means to me, and, in my
experience, with most people talking about OOP: they usually mean
hiding it from code outside the class while keeping it open to code
inside the class.  Which means "self.v_min=2" would work, but
"s.v_min=2" would not.  What you've done is to hide it from everyone,
so I wouldn't call it Data Hiding(tm), even if you have, technically,
hidden data.

The term I use for what you did here is "enforcing an invariant", and
I think it is an interesting feature and occasionally indispensible,
but it's also something Python's always been able to do.  Even in
Python 1.5, before properties and such, you could override __setattr__
to enforce invariants.


Carl Banks



More information about the Python-list mailing list