Inheritance and forward references (prototypes)

Steven D'Aprano steve at REMOVETHIS.cybersource.com.au
Sat Jun 20 12:21:18 EDT 2009


Lorenzo Di Gregorio wrote:

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

You don't actually explain what is the problem. Fortunately, I'm good at
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
> ---------------------------------------

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


class A(BaseA):
    pass

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




-- 
Steven




More information about the Python-list mailing list