Why less emphasis on private data?

Paul Boddie paul at boddie.org.uk
Sun Jan 7 18:02:55 CET 2007


Paul Rubin wrote:
>
>     class A:
>       __x = 3
>
>     class B(A):
>       __x = 4   # ok
>
>     class C(B):
>       __x = 5   # oops!
>
> Consider that the above three class definitions might be in separate
> files and you see how clumsy this gets.

What are you trying to show with the above? The principal benefit of
using private attributes set on either the class or the instance is to
preserve access, via self, to those attributes defined in association
with (or within) a particular class in the inheritance hierarchy, as
opposed to providing access to the "most overriding" definition of an
attribute. This is demonstrated more effectively with a method on class
A:

  class A:
      __x = 3
      def f(self):
          print self.__x # should always refer to A.__x

  class B(A):
      __x = 4

  class C(B):
      __x = 5

Here, instances of A, B and C will always print the value of A.__x when
the f method is invoked on them. Were a non-private attribute to be
used instead, instances of A, B and C would print the overridden value
of the attribute when the f method is invoked on them.

Paul




More information about the Python-list mailing list