[Tutor] Private members?

Steven D'Aprano steve at pearwood.info
Fri Feb 26 03:55:14 EST 2016


On Thu, Feb 25, 2016 at 11:59:21PM -0500, kay Cee wrote:
> Say I have a basic Circle class, for example:
> 
> class Circle:
>     def __init__(self, radius):
>         self.__radius = radius 
> 
> Does adding the double underscore make this member directly inaccessible to children of the Circle class?

No, but it makes it harder to do so by accident and annoying to do so 
deliberately. In order to access a double-underscore attribute like 
__radius, the child needs to know the name of the class which defined 
it:

class MyCircle(Circle):
    def method(self):
        try:
            print(self.__radius)
        except AttributeError:
            print("__radius not found!")
        r = self._Circle__radius
        print("self._Circle__radius:", r)


And an example in use:

py> obj = MyCircle(999)
py> obj.method()
__radius not found!
self._Circle__radius: 999



What happens here is that when you refer to "self.__radius" inside a 
method, Python mangles the name to "self._CLASSNAME__radius" instead. 
(For whatever the class is actually named.) This happens automatically, 
and is intended as protection against accidental name clashes between 
the parent class and its children.


> Also, I'd like to know if there are any side effects to programming classes this way?

Yes, it's usually annoying and unnecessary.

The usual advice given is not to bother with double underscores unless 
you are really, really sure you need them.


-- 
Steve


More information about the Tutor mailing list