newbie-question: private attributes

Mark McEahern marklists at mceahern.com
Tue Sep 17 10:28:15 EDT 2002


[T. Kaufmann]
> What is the difference between the two attributes in this class?
>
> class Test:
>
>      def __init__(self):
>
>          self.__var1 = 1 # I think this is a private attribute
>          self._var2  = 2 # ... and this? Maybe protected?

Short answer:

  Both of them are ways of indicating a variable is private.  Both of them
are private by convention only.

  _var requires no hoops to circumvent.
  __var variables are mangled, but you can access them by jumping through
simple hoops.

Consider this:

#!/usr/bin/env python

class Test:

     def __init__(self):

         self.__var1 = 1 # I think this is a private attribute
         self._var2  = 2 # ... and this? Maybe protected?

     def show(self):
         print self.__class__.__name__
         for k, v in self.__dict__.items():
             print "\t%s = %s" % (k, v)

     def dosomethingwithvar1(self):
         self.__var1 += 1

class SubclassOfTest(Test):

    def dosomethingwithvar1(self):
        try:
            self.__var1 += 1
        except AttributeError:
            print "expected"
        self._Test__var1 += 1

t = Test()

print t._var2
try:
    print t.__var1
except AttributeError:
    print "expected error"
print t._Test__var1

t.show()
t.dosomethingwithvar1()
t.show()

s = SubclassOfTest()
print s._var2
try:
    print s.__var1
except AttributeError:
    print "expected error"
print s._Test__var1

s.show()
s.dosomethingwithvar1()
s.show()

-





More information about the Python-list mailing list