Prevent creating new attributes outside __init__

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

    Actually, you don't want __setattr__, you want __slots__. Add __slots__ = ('foo', 'bar', 'baz') to the class body, and Python will make sure that there's only foo, bar and baz on any instance. But read the caveats the documentation lists!

提交回复
热议问题