[Tutor] Private members?
alan.gauld at btinternet.com
Fri Feb 26 03:36:03 EST 2016
On 26/02/16 04:59, 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?
The fastest way to answer that question would be for you to try
it in the interpreter!
>>> class C:
... def __init__(s,v): s.__v = v
>>> class D(C):
... def __init__(s,v): C.__init__(s,v)
... def printv(s): print s.__v
>>> d = D(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in printv
AttributeError: D instance has no attribute '_D__v'
> Also, I'd like to know if there are any side effects to programming classes this way?
Depends what you mean by side effects.
- The name gets mangled by the interpreter (actually by the
compiler I think)
- The variable is not directly accessible so if you need
access to the data you need to write accessors and
setters and/or create a property.
- The code is not idiomatic Python since we mostly
don't bother making things private.
But those are not really side-effects in a computing sense.
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:
More information about the Tutor