Prevent creating new attributes outside __init__

前端 未结 11 1529
迷失自我
迷失自我 2020-12-04 07:23

I want to be able to create a class (in Python) that once initialized with __init__, does not accept new attributes, but accepts modifications of existing attri

11条回答
  •  孤城傲影
    2020-12-04 07:55

    I like the "Frozen" of Jochen Ritzel. The inconvenient is that the isfrozen variable then appears when printing a Class.__dict I went around this problem this way by creating a list of authorized attributes (similar to slots):

    class Frozen(object):
        __List = []
        def __setattr__(self, key, value):
            setIsOK = False
            for item in self.__List:
                if key == item:
                    setIsOK = True
    
            if setIsOK == True:
                object.__setattr__(self, key, value)
            else:
                raise TypeError( "%r has no attributes %r" % (self, key) )
    
    class Test(Frozen):
        _Frozen__List = ["attr1","attr2"]
        def __init__(self):
            self.attr1   =  1
            self.attr2   =  1
    

提交回复
热议问题