Task:
Some module-level variables (such as named constants) need to be defined, and the customer Code cannot re-bind them;
Solution:
#coding = utf-8class _const(object): class ConstError(TypeError): pass def __setattr__(self,name,value): if name in self.__dict__: raise self.ConstError,"Can‘t rebind const(%s)" % name self.__dict__[name] = value def __delattr__(self,name): if name in self.__dict__: raise self.ConstError,"Can‘t unbind const(%s)" % name raise NameError,name import syssys.modules[__name__] = _const()
Usage:
1. Save the preceding code as Const. py and add the directory of the file to the SYS. Path directory;
2. Run Const. py.
3. input the following in Python shell:
Import const
# Test code
Const. Magic = 23
Note: currently, any customer code can import const and bind one attribute of the const module once, but only once;
Once an attribute has been bound, the program cannot rebind it or unbind it.
Const. Magic = 99 # Throw Const. consterror
Del Const. Magic # Throw Const. consterror
Cookbook 6.2 defines Constants