Inheritance and forward references (prototypes)

Piet van Oostrum piet at cs.uu.nl
Sat Jun 20 22:16:21 CEST 2009


>>>>> Steven D'Aprano <steve at REMOVETHIS.cybersource.com.au> (SD) wrote:

>SD> Lorenzo Di Gregorio wrote:
>>> Hi,
>>> 
>>> I'm wondering what would be the preferred way to solve the following
>>> forward reference problem:

>SD> You don't actually explain what is the problem. Fortunately, I'm good at
>SD> guessing, and I think I can guess what your problem is (see below):


>>> ---------------------------------------
>>> class BaseA(object):
>>> def __init__(self):
>>> return
>>> 
>>> class DebugA(BaseA):
>>> def __init__(self):
>>> return
>>> 
>>> # here I would have a prototype of class A which is the same as class
>>> BaseA
>>> 
>>> class B(object):
>>> def __init__(self):
>>> self.obj = A()
>>> return
>>> 
>>> if __name__ == "__main__":
>>> #    class A(BaseA): # Uncomment this for using BaseA objects
>>> #       pass
>>> class A(DebugA): # Uncomment this for using DebugA objects
>>> pass
>>> ---------------------------------------

>SD> Class A only gets defined if you run the module as a script. What you need
>SD> is to unconditionally define class A, outside of the if __name__ block:


>SD> class A(BaseA):
>SD>     pass

>SD> # A.__base__ = DebugA  ## Uncomment this line for debugging.

>>>A.__base__ = DebugA
TypeError: readonly attribute

Make that: A.__bases__ = DebugA,

>SD> -- 
>SD> Steven


-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list