Will python never intend to support private, protected and public?

Bill Mill bill.mill at gmail.com
Thu Sep 29 17:55:12 CEST 2005

> ___________________________________________
> class a:
>     i=0
>     def setI(iii):
>         if self.i!=iii:
>             self.i=iii
>             #do some extra works here, e.g, notify the observers that
>             #this property is changed, or do some logging things.
> ___________________________________________
> In the class "a" above, when "i" is changed, I will do some extra works,
> the extra works could be very import, so I want to keep i invisible
> to some others, they can only change i by the method setI. But python
> can't ensure i to be invisible, everyone can change it whenever they
> want! This is dangerous.

>>> class test(object):
...   __i = 0
...   def incr(self, n): self.__i += 1; print "incremented i"
...   def geti(self): print "got i"; return self.__i
...   i = property(geti, incr)
>>> t = test()
>>> t.i
got i
>>> t.i += 5
got i
incremented i
>>> t.i
got i
>>> dir(t)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash_
_', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr_
_', '__setattr__', '__str__', '__weakref__', '_test__i', 'geti', 'i', 'incr']
>>> #here's how the crazy hackers subclassing your code can break your super
... #special private variable!
>>> t._test__i += 6
>>> t.i
got i

But, if your users can't figure out that they shouldn't be changing
the variable called t._test__i without expecting side effects, what do
you think of the users of your class?

Python is for consenting adults.

Bill Mill
bill.mill at gmail.com

More information about the Python-list mailing list