James Stroud said unto the world upon 2005-12-09 20:39: > Brian van den Broek wrote: > >>Hi all, >> >>I've the following code snippet that puzzles me: >> >>class Base(object): >> __v, u = "Base v", "Base u" >> def __init__(self): >> print self.__v, self.u >> >>class Derived(Base): >> __v, u = "Derived v", "Derived u" >> def __init__(self): >> print self.__v, self.u >> super(Derived, self).__init__() >> >>d = Derived() >> >>When run (Python 2.4.2, IDLE 1.1.2), it produces: >> >> >>> >>Derived v Derived u >>Base v Derived u >> >>> >> >>What I expected was that all four emitted strings would contain "Derived".
<snip me -- Brian -- speculating on locus of my confusion> >>Thanks and best, >> >>Brian vdB > > > This is name mangling at work. Mangling turns self.__v in the Derrived > class's > __init__ method to self._Derrived__v and self.__v in the Base class's > __init__ > method to self._Base__v. These are different names bound to different values > and > are reflected as such. self.u is the same name in both cases and the value > was > bound in the Derrived class, and not re-bound in the Base class. > > James Thanks for the reply, James. Rereading the relevant section of the Tutorial: >> Any identifier of the form __spam (at least two leading >> underscores, at most one trailing underscore) is textually replaced >> with _classname__spam, where classname is the current class name >> with leading underscore(s) stripped. <http://docs.python.org/tut/node11.html#SECTION0011600000000000000000> I'm not sure how I came to think that names were mangled only with respect to calling code from outside class definitions. As I'd been confused, I naturally started thinking of ways to clarify the docs. But, I've come to think that the error was wholly mine. Thanks for the help, Brian vdB -- http://mail.python.org/mailman/listinfo/python-list