Declaring a class level nested class?
Jean-Michel Pichavant
jeanmichel at sequans.com
Thu Dec 3 08:13:19 EST 2009
Chris Rebert wrote:
> On Wed, Dec 2, 2009 at 8:55 PM, cmckenzie <mckenzie.c at gmail.com> wrote:
>
>> Hi.
>>
>> I'm new to Python, but I've managed to make some nice progress up to
>> this point. After some code refactoring, I ran into a class design
>> problem and I was wondering what the experts thought. It goes
>> something like this:
>>
>> class module:
>> nestedClass
>>
>> def __init__():
>> self.nestedClass = nested()
>> print self.nestedClass.nestedVar
>>
>> class nested():
>> nestedVar = 1
>> def __init__(self):
>> print "Initialized..."
>>
>> I can't figure out what the correct way to construct the "nested"
>> class so it can belong to "module".
>>
>> I want a class level construct of "nested" to belong to "module", but
>> I keep getting nestedClass isn't defined.
>>
>
> Here's the scoping reason why it fails (remember that the nested class
> is a class variable of the containing class):
>
> [snip interesting reminder/faq]
>
> However, there's pretty much no reason to nest classes anyway in
> Python (it's not Java!).
A little bit off topic,ahere is a nested class pattern I'm using quite
often :
class Device
"""Holds the different device services."""
class OS: # UPPERCASE means it holds constants
"""Operating system of one device."""
VXWORKS = 'vxWorks'
ECOS = 'ecos'
def init(self, _os = None):
self.os = _os
device = Device(Device.OS.VXWORKS)
Whenever I get a Device instance in my code I can match its OS without
tedious imports:
# no "from whatever import Device" is required
if device.os is device.OS.VXWORKS:
print 'you are using vxWorks'
I'm using this pattern whenever I can now:
1/ it removes all magically 'inside code' defined strings or numbers,
only class attributes are used.
2/ if required, it allows to write complete and detailed documentation
for nested class constants
3/ you can match attributes with the nested class values without further
import, everything is accessible from the instance itself
JM
More information about the Python-list
mailing list