[Tutor] Protected methods/variables

w chun wescpy at gmail.com
Tue Apr 4 19:21:48 CEST 2006


> I have missed protected method/variables in Python. How do you declare
> methods/variables used only by a class and their derived classes?

hi Ktalà,

welcome to Python!  you missed "protection" in OOP with Python bceause
there are no such declarations in Python!

1) there is a privacy *hint*, which is using "__" to start a variable
or method name with, e.g.,  def __myMaybePrivateMethod(self,...). 
this does name-mangle the attribute at run-time, however the algorithm
is fairly well-known and easy to crack:
self._CLASS__myMaybePrivateMethod().  for more on this see,:
http://docs.python.org/tut/node11.html#SECTION0011600000000000000000

2) however, with Python's new-style classes introduced back in 2.2,
there are much more powerful security mechanisms you can employ so
that you can customize any or all of your attributes (data attributes
[variables] or methods) to give it the most fine-grained security you
can imagine.

- you can use property() for your attributes to assign a getter,
setter, and deleter method that get executed every time someone tries
to access, set, and delete an instance attribute:
 |  class C(object):
 |      def getx(self): return self.__x
 |      def setx(self, value): self.__x = value
 |      def delx(self): del self.__x
 |      x = property(getx, setx, delx, "I'm the 'x' property.")

- you can use descriptors (__get__, __set__, __delete__) that get
executed every time someone tries to access, set, and remove your
object... this allows you to really customize instances and how
attribute access occurs.  using descriptors, you can bypass the
regular way of attribute search, i.e., x.foo normally looks at object
'x' for 'foo', and if not found, searches type(x) for 'foo', and then
it progresses this search to ancestor classes.  with descriptors, you
can override this default behavior to make instances differ from one
another.  in fact, properties (as seen above) is an example of a
descriptor!

- you can use __slots__ to restrict arbirtrary creation of (dynamic)
instrance attributes

- you can even customize how classes are created (by using metaclasses
and __metaclass__)

so as you can see, you can do a lot more with Python classes than what
you can do with 'private', 'protected', 'friend', or 'protected
friend'.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list