Const is implemented in Python
- 2020-04-02 14:31:08
- OfStack
The python language itself does not provide const, but it is common to encounter situations where const is needed in real development, and since the language itself does not have this expense, there are a few tricks you need to use to achieve this
Define the const class as follows
import sys
class Const(object):
class ConstError(TypeException): pass
def __setattr__(self, key, value):
if self.__dict__.has_key(key):
raise self.ConstError, "Changing const.%s" % key
else:
self.__dict__[key] = value
def __getattr__(self, key):
if self.__dict__.has_key(key):
return self.key
else:
return None
sys.modules[__name__] = Const()
Sys. modules[name] can be used to get a module object, and can get the module properties through the object, here USES sys.modules to inject a Const object into the system dictionary to achieve the function of actually getting a Const instance when executing import Const,sys.module is described in the document as follows
sys.modules
This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.
Sys. modules[name] = Const() this statement replaces the Const in the list of modules the system has loaded with Const(), an instance of Const
In this way, the constants needed for the entire project should be defined in a file, as follows
from project.utils import const
const.MAIL_PROTO_IMAP = 'imap'
const.MAIL_PROTO_GMAIL = 'gmail'
const.MAIL_PROTO_HOTMAIL = 'hotmail'
const.MAIL_PROTO_EAS = 'eas'
const.MAIL_PROTO_EWS = 'ews'
The first thing to note here is the difference between an import module and a from module import in python
1. The import module simply adds the name of the module to the local dictionary of the target file and does not need to explain the module
2. From module import XXX, we need to load the module interpretation into memory, and then add the corresponding part to the local dictionary of the target file
3. Code in a python module is executed only once when it is first imported
From project.utils import const, sys.modules[name] = const () occurs. At this time, the const module has been loaded into memory, the const object is already in the system dictionary, and the const instance can be used later
When constant values are needed in other files, they are called as follows
from project.apps.project_consts import const
print const.MAIL_PROTO_IMAP