[Tutor] Private members?
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
print("__radius not found!")
r = self._Circle__radius
And an example in use:
py> obj = MyCircle(999)
__radius not found!
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.
More information about the Tutor