python development practices?
Chris Tavares
christophertavares at earthlink.net
Wed Oct 31 18:57:16 EST 2001
"Cliff Wells" <logiplexsoftware at earthlink.net> wrote in message
news:mailman.1004563112.32516.python-list at python.org...
[... snip ...]
>
> Encapsulation is as much a part of data hiding as private variables.
> However, it would be nice to have a mechanism so that derived classes
> wouldn't have to be careful of accidentally stepping on the attributes of
> base classes. As I said earlier, a class should be a "black box".
Authors
> of derived classes shouldn't have to look at the internals of base classes
to
> avoid this, especially since, as we were discussing, the internals of the
> base class could conceivably change, introducing name-collisions in
derived
> classes. A single underscore will not prevent this. For instance:
>
> class Base:
> def __init__(self):
> self._foo = 1
>
> class Derived(Base):
> def __init__(self):
> Base.__init__(self)
> self._x = 1
> self._y = 2
>
> No problem here, but later, the author of Base decides to add a self._x to
> Base. Now Derived is undoubtedly broken and it won't be clear why. A
> private variable mechanism that could prevent this scenario would be a
> definite benefit.
>
This scenario is precisely why the two underscore name mangling scheme was
added to python. Rewrite your example as:
class Base:
def __init__(self, x):
self.__x = x
def print_base_x(self):
print self.__x
class Derived( Base ):
def __init__(self, base_x, dev_x):
Base.__init__(self, base_x)
self.__x = dev_x
def print dev_x(self):
print self.__x
d = Derived( 5, "hi there!" )
d.print_base_x()
prints 5
d.print_dev_x()
prints Hi There!
So, the mechanism you're asking for is already there. Wether it's pretty or
not is a different question. But it does work, and it's implemented now.
-Chris
More information about the Python-list
mailing list