Prevent creating new attributes outside __init__

前端 未结 11 1506
迷失自我
迷失自我 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:48

    Here is approach i came up with that doesn't need a _frozen attribute or method to freeze() in init.

    During init i just add all class attributes to the instance.

    I like this because there is no _frozen, freeze(), and _frozen also does not show up in the vars(instance) output.

    class MetaModel(type):
        def __setattr__(self, name, value):
            raise AttributeError("Model classes do not accept arbitrary attributes")
    
    class Model(object):
        __metaclass__ = MetaModel
    
        # init will take all CLASS attributes, and add them as SELF/INSTANCE attributes
        def __init__(self):
            for k, v in self.__class__.__dict__.iteritems():
                if not k.startswith("_"):
                    self.__setattr__(k, v)
    
        # setattr, won't allow any attributes to be set on the SELF/INSTANCE that don't already exist
        def __setattr__(self, name, value):
            if not hasattr(self, name):
                raise AttributeError("Model instances do not accept arbitrary attributes")
            else:
                object.__setattr__(self, name, value)
    
    
    # Example using            
    class Dog(Model):
        name = ''
        kind = 'canine'
    
    d, e = Dog(), Dog()
    print vars(d)
    print vars(e)
    e.junk = 'stuff' # fails
    

提交回复
热议问题