
python3 封装常量文件
发布日期:2021-05-14 23:04:14
浏览次数:21
分类:精选文章
本文共 1980 字,大约阅读时间需要 6 分钟。
constant.py: Custom Constant Handling
A custom class for handling constant values and enforcing naming conventions.
Class Definition
The `_const` class defines a mechanism for custom constant handling, ensuring that constant values and their names follow specific rules.
Implementation Details:
- Exception Handling - Two specific exceptions are defined:
- ConstError: Raised when attempting to reassign a constant value.
- ConstCaseError: Raised when constant name does not conform to specified naming conventions.
- Method Overloading via __setattr__ - Custom behavior for attribute assignment:
- If the attribute already exists in the instance's dictionary, it raises a ConstError to prevent reassignment.
- All constant names must be uppercase letters; lowercase names will throw a ConstCaseError.
- The attribute is then set in the instance's dictionary for future reference.
Demostration: Usage in Practice
Example: constant.py
Here's how the constant class is implemented in the constant.py file:
from constant import constclass _const: # Custom exception definitions class ConstError(PermissionError): pass class ConstCaseError(ConstError): pass def __setattr__(self, name, value): if name in self.__dict__: raise self.ConstError("Cannot assign value to constant {0}".format(name)) if not name.isupper(): raise self.ConstCaseError("const name {0} is not all uppercase".format(name)) setattr(self, name, value) const = _const()const.PI = 3.14
Example Usage: demo.py
Here's how the constant values are used in a separate application (demo.py):
from constant import constprint(const.PI) # Outputs: 3.14
This implementation ensures that constant values remain immutable and Follow consistent naming conventions, which is essential for maintaining reliable codebase.