Re: Underscore data hiding (was python development practices?)
by Barry A. Warsaw other posts by this author
Nov 1 2001 7:46AM messages near this date
Re: Underscore data hiding (was python development practices?)
|
Re: Underscore data hiding (was python development practices?)
> >>>> "MF" == Martijn Faassen <m.faassen@[...].nl> writes:
MF> The double underscore is required for name mangling, but I
MF> don't really like the name mangling; it gets in the way. I
MF> just want to give the programmer a hint that some attribute is
MF> private, and I use a single underscore for this, and many
MF> Python programmers with me.
FWIW, the double-leading-underscore-no-trailing-double-underscore name
mangling rule wasn't added specifically for data hiding. It was so
that a class that was designed to be subclassed could have a namespace
that subclasses couldn't accidently trample on:
-------------------- snip snip --------------------
class A:
def __init__(self):
self._my_private_counter = 0
def countup(self):
self._my_private_counter += 1
print self._my_private_counter
class B(A):
def __init__(self):
A.__init__(self)
self._my_private_counter = 10
def countdown(self):
self._my_private_counter -= 1
print self._my_private_counter
> >> b = B()
> >> b.countup()
11 # huh, why isn't this 1?
class A:
def __init__(self):
self.__my_private_counter = 0
def countup(self):
self.__my_private_counter += 1
print self.__my_private_counter
class B(A):
def __init__(self):
A.__init__(self)
self.__my_private_counter = 10
def countdown(self):
self.__my_private_counter -= 1
print self.__my_private_counter
> >> b = B()
> >> b.countup()
1 # ah that's better!
-------------------- snip snip --------------------
IOW, B's designer shouldn't have to know anything about A's private
interface in order to be correctly implemented. Name mangling
preserves the integrity of A's private API.
Of course, B's designer must know about A's inherited (i.e. protected)
API in order to be correctly implemented. In that situation, many
different conventions exist. My own personal one is to prefix
protected API attributes with a single underscore (and document them
;).
-Barry
--
http://mail.python.org/mailman/listinfo/python-list
Thread:
Peter Wang
Peter Hansen
Toby Dickenson
Tim Peters
Steve Holden
Steve Holden
Cliff Wells
Tim Peters
Martijn Faassen
Cliff Wells
Cliff Wells
Martijn Faassen
Martijn Faassen
Paul Rubin
Russell E. Owen
Barry A. Warsaw
Martijn Faassen
Peter Wang
Skip Montanaro
John Roth
David Bolen
Peter Wang
Peter Wang
Skip Montanaro
Chris Tavares
Darren Collins
David Bolen
Paul Rubin
Paul Rubin
Peter Wang
F Basegmez
Richard Jones
Richard Jones
Neal Norwitz
Graham Ashton
Peter Wang
Russell E. Owen
Skip Montanaro
Cliff Wells
Hung Jung Lu
Wade Leftwich
Peter Wang
Peter Wang
Peter Wang
Chris Gonnerman
Paul Rubin
Andrew Dalke
Paul Rubin
Luigi Ballabio
Paul Rubin
Tim Peters
John Roth
Paul Rubin
Richard Jones
|