python, __slots__, and “attribute is read-only”

后端 未结 5 1222
無奈伤痛
無奈伤痛 2021-02-02 11:59

I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:

<         


        
5条回答
  •  野性不改
    2021-02-02 12:07

    __slots__ works with instance variables, whereas what you have there is a class variable. This is how you should be doing it:

    class MyClass( object ) :
      __slots__ = ( "m", )
      def __init__(self):
        self.m = None
    
    a = MyClass()
    a.m = "?"       # No error
    

提交回复
热议问题