python定义常量类,禁止修改类属性
class NoModifyMeta(type):
def __setattr__(cls, key, value):
raise AttributeError(f"Cannot modify class attribute '{key}'")
class ConstDict(metaclass=NoModifyMeta):
def __setattr__(self, key, value):
raise AttributeError(f"Cannot modify class attribute '{key}'")
class A(ConstDict):
b = 1
print(A.b) # 1
print(A().b) # 1
A().b = 1 # 报错
A.b = 1 # 报错

浙公网安备 33010602011771号