Declaring a class level nested class?

Lie Ryan lie.1296 at gmail.com
Thu Dec 3 10:43:18 EST 2009


On 12/4/2009 1:59 AM, cmckenzie wrote:
> Sigh, I'm using Google Groups and it seems I can't see my original
> post and everyone's replies. I'm really keen to reply back, so I'll
> just re-post my follow up for now and make sure I don't make a habit
> of this. (I'll get a news reader) Here goes:
>
> I agree, I'm C# and Java influenced, but I've got some messy Perl
> experience too.
>
> It was late when I posted my example, so I don't think I made my
> question clear enough. I want to be able to construct a class level
> class variable, so its global to the class,

"global to the class" that's contradictory!

> then reference it from a
> class method.


> I wrote a web server that uses reflection to dynamically
> load modules which are mapped to url paths. e.g. module "search.py"
> maps to "search.html",

Be careful of someone requesting an ../insecure.html

> etc... It all works great, but I want my
> modules to be able to __init__ classes that belong to the module, then
> when a request comes in and is passed to the module, I can reference
> that initialized class.

When a module is "import"-ed, it's body is executed, unless you put it 
inside a if __name__ == '__main__': block which is only executed when 
the module itself is executed (instead of being imported). Basically, 
the module's body is like the module's __init__()

That way if your directory is like this:
/data
- /__init__.py
- /one.py
/run_server.py

your one.py would contains something like:

class MyClass(object):
    ...
instance = MyClass()


and your run_server.py would reference the already instantiated module 
in the class as such:

from data.one import instance

# serve something using the instance




> The declaration of a class level nestedClass class variable is wrong,
> but I was hoping someone could just say, "dummy, this is how to
> declare a class variable when you can't construct it just yet",



> or
> "you have to construct an empty version of nestedClass at the class
> level, then just re-construct it with any parameters during __init__".

That sounds like C/C++ forward declaration. Not something you'd need in 
a language that has dynamic name resolution.

>
> class module:
>    nestedClass
>
>    def __init__():
>       self.nestedClass = nested(10)
>       print self.nestedClass.nestedVar
>
>    def getNestedVar(self):
>       return self.nestedClass.nestedVar
>
>    class nested():
>       nestedVar = 1
>       def __init__(self, value):
>          nestedVar = value
>          print "Initialized..."
>
> Thanks and sorry for double posting, it won't happen again.




More information about the Python-list mailing list