[Tutor] subclass problem: __names and type-checking

Brian van den Broek broek at cc.umanitoba.ca
Mon Oct 10 01:24:44 CEST 2005

Python said unto the world upon 2005-10-08 12:40:
> Traceback (most recent call last):
>    File "C:/Python24/foofoofoo.py", line 26, in -toplevel-
>      s2 = Sub2()
>    File "C:/Python24/foofoofoo.py", line 22, in __init__
>      super(Sub2, self).__init__()
>    File "C:/Python24/foofoofoo.py", line 10, in __init__
>      if type(self) == __TwoUnderBase:  # What to write here
> NameError: global name '_TwoUnderBase__TwoUnderBase' is not defined
> Within a class, __ prefixes mangle the name to include the class name as
> part of the name.  However, it appears that within a class statement,
> the __ prefix is not mangled.  This is good for you because otherwise
> the inheritance would not work.  However, it appears to make it
> impossible to directly reference the class name from within the class.
> You may want to rethink the idea of using __ prefixes in the class name.
> Normally __ is used to "privatize" attributes within a class.

Hi all,

I did give up the use of __ names in the case at hand. But I just 
posted a question about how to reference a __ class name from with the 
class on comp.lang.python. I used the code up-thread here. The F-bot 

class __TwoUnderBase(object):
       def __init__(self):
           if self.__class__.__name__ == "__TwoUnderBase":
               print "From __TwoUnderBase"
               print "From subclass",

which does the trick. Thought I'd post it here in case of future googling.

Best to all,


More information about the Tutor mailing list