Python implements the constant (Const) function, pythonconst
The python language does not provide const, but const is often used in actual development. Because the language itself does not have such expenditure, you need some skills to implement this function.
The const class is defined as follows:
Copy codeThe Code is 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 ()
Use sys. modules [name] can obtain a module object and obtain the attributes of the module through this object. sys is used here. modules injects a Const object into the system dictionary to implement the function of actually obtaining a const instance when executing import Const, sys. the description of the module in this document is as follows:
Copy codeThe Code is 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 loaded modules with Const (), that is, a Const instance.
In this way, the constants required for the entire project should be defined in a file, as follows:
Copy codeThe Code is 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 = 'done'
First, we need to explain the differences between import module and import from module in python.
1. The import module only adds the module name to the local Dictionary of the target file.
2. from module import xxx needs to interpret the module and load it into the memory. Then, add the corresponding part to the local Dictionary of the target file.
3. The code in the python module is executed only once when it is imported for the first time.
From project. when utils import const, sys. modules [name] = Const (). At this time, the const module has been loaded into the memory, and the system dictionary has a Const object. Then you can use the Const instance.
To use a constant value in other files, call
Copy codeThe Code is as follows:
From project. apps. project_consts import const
Print const. MAIL_PROTO_IMAP