python,__slots__和“attribute”是只读的“ [英] python, __slots__, and "attribute is read-only"
问题描述
class MyClass(object):
m = None#my attribute
__slots__ =(m)#确保对象没有_m etc
a = MyClass()#创建一个
am =? #这里是一个PROBLEM
但是,运行这个简单的代码后,我得到一个非常奇怪的错误:
追溯(最近的最后一次呼叫):
文件test.py,第8行,< module>
a.m =?
AttributeError:'test'对象属性'm'是只读
有没有聪明的程序员谁可以节省一点时间,并启发我有关只读错误?
当您声明实例变量使用 __ slots __
,Python创建一个描述符对象作为具有相同名称的类变量。在你的情况下,这个描述符被您在以下行定义的类变量 m
覆盖:
m =无#我的属性
do:不要定义一个名为 m
的类变量,并在 m
> __ init __ 方法。
class MyClass(object):
__slots__ =(m ,)
def __init __(self):
self.m =无
a = MyClass()
am =?
作为附注,单元素元组在元素后需要一个逗号。两者都在你的代码中工作,因为 __ slots __
接受单个字符串或一个可迭代/序列的字符串。通常,要定义一个包含元素 1
的元组,请使用(1,)
或 1,
而不是(1)
。
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:
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
But after running this simple code, I get a very strange error:
Traceback (most recent call last):
File "test.py", line 8, in <module>
a.m = "?"
AttributeError: 'test' object attribute 'm' is read-only
Is there any wise programmer who can spare a bit of their time and enlighten me about "read-only" errors?
When you declare instance variables using __slots__
, Python creates a descriptor object as a class variable with the same name. In your case, this descriptor is overwritten by the class variable m
that you are defining at the following line:
m = None # my attribute
Here is what you need to do: Do not define a class variable called m
, and initialize the instance variable m
in the __init__
method.
class MyClass(object):
__slots__ = ("m",)
def __init__(self):
self.m = None
a = MyClass()
a.m = "?"
As a side note, tuples with single elements need a comma after the element. Both work in your code because __slots__
accepts a single string or an iterable/sequence of strings. In general, to define a tuple containing the element 1
, use (1,)
or 1,
and not (1)
.
这篇关于python,__slots__和“attribute”是只读的“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!