我想在Python中创建一个带有几个属性的对象,并且希望保护自己不会意外使用错误的属性名称。代码如下:
class MyClass( object ) :
m = None # my attribute
__slots__ = ( "m" ) # ensure that object has no _m etc
a = MyClass() # create one
a.m = "?" # here is a PROBLEM
但是在运行这个简单的代码后,我得到了一个非常奇怪的错误:
Traceback (most recent call last):
File "test.py", line 8, in <module>
a.m = "?"
AttributeError: 'test' object attribute 'm' is read-only
有没有聪明的程序员能抽出一点时间并启迪我关于“只读”错误的问题?
AttributeError: 'MyClass'对象属性'm'是只读的
。 - Mr_and_Mrs_D