virtual inner classes in python?

Peter Hansen peter at engcorp.com
Tue Sep 9 18:31:59 EDT 2003


kasper graversen wrote:
> 
> I've just started learning python. I see methods are declared virtual by
> default as in Java. Nice. However, the inner class construct seems to be
> even weaker as that of Java. Not nice! :-( Why are inner classes not
> virtual? will they be in a near future? What other language can you
> recomend, if python cannot provide what I need?
> 
> My problem is that in the __init__ below, I cannot instantiate "Foo" but
> have to explicate "Test.foo".. secondly, I want to instantiate the "Foo" in
> test2 rather than in tester in the current example..
> 
> class Test:
>     def __init__(self):
>         lala = Test.Foo()
>         lala.show()
>         class Foo:
>         def show(self):
>             print "Test.foo.show"

With the tabs that you used, the above formatting is what some of us
saw.  It seems you meant for "class Foo" to appear at the same level
of indentation as the "def __init__", right?

As for "declared virtual by default", I don't think this is quite
correct for Python.  All methods are always virtual in Python, 
unless one goes to extremes to simulate some other effect, I think.

Anyway, I believe the problem you are experiencing stems from a lack
of understanding of how Python finds things in its "namespaces".  
This is a key concept to issues such as the one you are investigating,
and you won't get far if you assume Python is anything like Java
or other static languages in this respect.

First, you need to specify Test.Foo because otherwise you are 
asking for a Foo that is found in the global (module) namespace.
You could also use "self.Foo" in this case, though it might be
considered slightly less clear, but I have a feeling it would 
do roughly what you want, whatever that is.  (You didn't really
make it clear what you want, as near as I can tell.)

-Peter




More information about the Python-list mailing list