inheritance and private attributes
Peter Otten
__peter__ at web.de
Wed Apr 21 15:46:17 EDT 2004
KN wrote:
>
> I've run into such problem:
>
> I have something like this:
>
> class A(object):
> def __init__(self):
> self.__value = None
>
> class B(A):
> def test(self):
> if self.__value:
change the above to
if self._A__value:
> print "Ok."
> else:
> print "Empty."
>
>>>> b = B()
>>>> b.test()
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 3, in test
> AttributeError: 'B' object has no attribute '_B__value'
>
> Why I have no access to private attribute from a class that
> inherits other class? I just want to have access to the same
> private variables but also to extend its functionality by
> adding a method that operates on those private attributes and
> I'm unable to do so.
>
> Is this normal behaviour? What should I do if I want to
> override method and use private attribute, or just add
> some other method which changes this attribute?
Python performs name mangling for attributes starting with two underscores.
This is meant to avoid accidental nameclashes of attributes that are rather
an implementation detail than of interest to subclasses and the wider
public. I like many others use attribute names with a *single* leading
underscore (i. e. no name mangling) to signal "this is may change without
prior notice" while omitting artificial hurdles.
This is also known as treating programmers as adults :-)
Peter
More information about the Python-list
mailing list