Question about classes and possible closure.

Steven W. Orr steveo at syslang.net
Wed Feb 21 17:30:26 EST 2007


This is all an intro learning experience for me, so please feel free to 
explain why what I'm trying to do is not a good idea.

In the Cookbook, they have a recipe for how to create global constants.

-----------------
class _const:
     class ConstError(TypeError): pass
     def __setattr__(self,name,value):
         if self.__dict__.has_key(name):
             raise self.ConstError, "Can't rebind const(%s)"%name
         self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()
----------------

I'd like to be able to create constants within a class. (Yes I understand 
that uppercase names is a far better and easier convention but this is a 
learning experience for me.)

I can't get this to work, but my idea is that MyClass is defined thusly:

class ConstError(TypeError): pass
class Myclass:
     def mprint(self):
         print "C1 = ", self._C1

     # Define a subclass to create constants. It refs upself to access
     # the uplevel copy of self.
     class _const:
         class ConstError(TypeError): pass
         def __setattr__(_upself,name,value):
             if upself.__dict__.has_key(name):
                 raise self.ConstError, "Can't rebind const(%s)"%name
             else:
                 print "Just set something"
             upself.__dict__[name]=value

     # I want the const instance to be contained in this class so I
     # instantiate here in the constructor.
     def __init__(self):
         upself = self
         upself.consts = const()
         upself.consts._C1 = 0
         setattr(upself.consts, "_C1", 44)
         self = upself

Then the call in another file is this:
#! /usr/bin/python
from c2 import Myclass
foo = Myclass()
foo.mprint()
# end

Is it possible to nest a class in another class and is it possible to make 
this work?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net



More information about the Python-list mailing list