__Classes and type tests

Brian van den Broek broek at cc.umanitoba.ca
Sun Oct 9 23:35:56 CEST 2005


Hi all,

The code below exhibits an attempt to refer to the type of a __Class 
from within a method of that class. I've been unable to figure out how 
to make it work as I want, and would appreciate any insight.

The problem emerged out of a bad design that the good folks on the 
tutor list helped me repair. With that repair, I no longer need nor 
want to do this sort of thing in actual code. But the academic issue 
"How/Can it be done?" still itches.


class _OneUnderBase(object):
      def __init__(self):
          if type(self) == _OneUnderBase:
              print "From _OneUnderBase"
          else:
              print "From subclass",

class __TwoUnderBase(object):
      def __init__(self):
          # What to write in the if type() test to secure same
          # behaviour as _OneUnderBase
          if type(self) == __TwoUnderBase:
              print "From __TwoUnderBase"
          else:
              print "From subclass",

class SubOne(_OneUnderBase):
      def __init__(self):
          super(SubOne, self).__init__()
          print "SubOne"

class SubTwo(__TwoUnderBase):
      def __init__(self):
          super(SubTwo, self).__init__()
          print "SubTwo"

s1 = SubOne()
s2 = SubTwo()


When run, this gives:

 >>>
 From subclass SubOne
Traceback (most recent call last):
   File "C:/Documents and Settings/Owner/My 
Documents/PythonFiles/foo.py", line 28, in ?
     s2 = SubTwo()
   File "C:/Documents and Settings/Owner/My 
Documents/PythonFiles/foo.py", line 24, in __init__
     super(SubTwo, self).__init__()
   File "C:/Documents and Settings/Owner/My 
Documents/PythonFiles/foo.py", line 12, in __init__
     if type(self) == __TwoUnderBase:
NameError: global name '_TwoUnderBase__TwoUnderBase' is not defined
 >>>

So, the _OneUnderBase version works fine. I've been unable to work out 
what to write in the __TwoUnderBase version to make it work the same.

(In case it is not clear, I'm aiming at the output:
 From subclass SubOne
 From subclass SubTwo
)

I *think* I understand how __ name mangling works when making 
references from one module to another. But I cannot work it out 
reference to the class itself from within a __ class.

Should it matter: Python 2.4.2 on Win32.

Thanks,

Brian vdB




More information about the Python-list mailing list