__Classes and type tests

Peter Otten __peter__ at web.de
Mon Oct 10 02:56:11 EDT 2005


Brian van den Broek wrote:

> 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.

Define the method outside the class to defeat mangling: 

>>> def __init__(self):
...     if type(self) == __Two:
...             print "two leading underscores"
...
>>> class __Two(object):
...     __init__ = __init__
...
>>> __Two()
two leading underscores
<__main__.__Two object at 0x4029360c>

Peter




More information about the Python-list mailing list