Prevent creating new attributes outside __init__

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

    What about this:

    class A():
        __allowed_attr=('_x', '_y')
    
        def __init__(self,x=0,y=0):
            self._x=x
            self._y=y
    
        def __setattr__(self,attribute,value):
            if not attribute in self.__class__.__allowed_attr:
                raise AttributeError
            else:
                super().__setattr__(attribute,value)
    

提交回复
热议问题