Prevent creating new attributes outside __init__

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

    If someone is interested in doing that with a decorator, here is a working solution:

    from functools import wraps
    
    def froze_it(cls):
        cls.__frozen = False
    
        def frozensetattr(self, key, value):
            if self.__frozen and not hasattr(self, key):
                print("Class {} is frozen. Cannot set {} = {}"
                      .format(cls.__name__, key, value))
            else:
                object.__setattr__(self, key, value)
    
        def init_decorator(func):
            @wraps(func)
            def wrapper(self, *args, **kwargs):
                func(self, *args, **kwargs)
                self.__frozen = True
            return wrapper
    
        cls.__setattr__ = frozensetattr
        cls.__init__ = init_decorator(cls.__init__)
    
        return cls
    

    Pretty straightforward to use:

    @froze_it 
    class Foo(object):
        def __init__(self):
            self.bar = 10
    
    foo = Foo()
    foo.bar = 42
    foo.foobar = "no way"
    

    Result:

    >>> Class Foo is frozen. Cannot set foobar = no way
    

提交回复
热议问题