如果使用的旧技巧
__slots__不适合您,则此方法或它的某些变体可以做到:只需编写
__setattr__您的元类的方法来保护您。在此示例中,我阻止分配新属性,但允许修改现有属性:
def immutable_meta(name, bases, dct): class meta(type): def __init__(cls, name, bases, dct): type.__setattr__(cls,"attr",set(dct.keys())) type.__init__(cls, name, bases, dct) def __setattr__(cls, attr, value): if attr not in cls.attr: raise AttributeError ("Cannot assign attributes to this class") return type.__setattr__(cls, attr, value) return meta(name, bases, dct)class A: __metaclass__ = immutable_meta b = "test"a = A()a.c = 10 # this worksA.c = 20 # raises valueError
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)