inherrited private class varriables
holger krekel
pyth at devel.trillke.net
Mon Jun 17 19:10:32 EDT 2002
Uwe Mayer wrote:
> hi,
>
> why can't i access a class private varriable from within a predecessor?
> f.e.
>
> class parent:
> __length = 5
> def __init__(self): pass
> def action(self):
> print self.__class__.__length
>
> class child(parent):
> __length = 10
> def __init__(self): pass
>
> test = child()
> test.action()
>
> will print 5, instead of 10. why?
short answer:
private names are obtained by textual replacement.
child.__length and parent.__length may look similar
but the interpreter really sees [*]
child._child__length and parent._parent__length
and refuses to override. Think 'macro-preprocessor'.
long answer from http://www.python.org/doc/1.5/tut/node67.html :
Any identifier of the form __spam (at least two leading
underscores, at most one trailing underscore) is now textually
replaced with _classname__spam, where classname is the current
class name with leading underscore(s) stripped. This mangling
is done without regard of the syntactic position of the
identifier, so it can be used to define class-private instance
and class variables, methods, as well as globals, and even to
store instance variables private to this class on instances
of other classes.
regards,
holger
[*] if you want a proof 'import dis ; dis.dis(parent.action)'
More information about the Python-list
mailing list