python 中常量的实现
·
方法一,通过枚举类型实现
- 缺点可以动态添加新属性
-代码实现
from enum import Enum
class Constants(Enum):
AGE:int = 18
NAME:str = "TOM"
# Constants.AGE = 20 # AttributeError: cannot reassign member 'AGE'
# Constants.WEIGHT = 100 # can add new attributeerror
方法二通过__setattr__ 和Type
- 代码实现
from typing import Union
class MetaConstant(type):
ALLOWED_ATTR = {
}
def __setattr__(cls, name:str, value:Union[str, int, float]):
name = name.upper()
if name not in cls.ALLOWED_ATTR:
raise AttributeError(f"Cannot set class attribute '{name}' on class '{cls.__name__}'")
elif hasattr(cls, name):
raise AttributeError(f"Cannot modify Constants attribute {name}")
super().__setattr__(name, value)
class Constants(metaclass=MetaConstant):
ALLOWED_ATTR = {
"AGE",
"NAME"
}
AGE:int = 18
NAME:str = 'TOM'
print(Constants.AGE)
# Constants.AGE = 20 # AttributeError: Cannot modify Constants attribute AGE
# Constants.weight = 100 # AttributeError: Cannot set class attribute 'WEIGHT' on class 'Constants'
更多推荐
所有评论(0)