python定义常量类,禁止修改类属性

NAVYSUMMER / 2023-07-28 / 原文

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        # 报错