[英]Missing dunders for list type in attrs.asdict()?
I was trying to create a nesting of list()
class using Python attrs
decoractors, and noticed that the attrs.asdict()
did not work at some level of subvariables. 我试图使用Python
attrs
装饰器创建list()
类的嵌套,并注意到attrs.asdict()
在某些子变量级别上不起作用。 Such that: 这样:
attrs.asdict(mlle)
displays ok attrs.asdict(mlle)
显示正常 attrs.asdict(mlle.list_of_list_of_elements)
# FAILS attrs.asdict(mlle.list_of_list_of_elements)
#失败 attrs.asdict(mlle.list_of_list_of_elements[0])
displays ok attrs.asdict(mlle.list_of_list_of_elements[0])
显示正常 My working example is: 我的工作示例是:
import attr
@attr.s
class MyElement(object):
element = attr.ib(default="mydefault", type=str)
@attr.s(slots=True)
class MyListOfElements(object):
one_element = attr.ib(default=attr.Factory(MyElement))
list_of_elements = attr.ib(default=attr.Factory(list), type=list)
def add(self, le):
self.list_of_elements.append(le)
@attr.s(slots=True)
class MyListOfList(object):
version = attr.ib(default=None, type=str)
list_of_list_of_elements = attr.ib(default=attr.Factory(list)) # Where's the dunder for this list?
e1 = MyElement("1.1.1.1")
e1_1 = MyElement("11.11.11.11")
le1 = MyListOfElements()
le1.add(e1)
le1.add(e1_1)
print("le1:", le1)
e2 = MyElement("2.2.2.2")
le2 = MyListOfElements(e2)
le2.list_of_elements.append(e2)
print("le2:", le2)
mlle = MyListOfList()
print("mlle:", mlle)
mlle.list_of_list_of_elements.append(le1)
mlle.list_of_list_of_elements.append(le2)
print("mlle:", mlle)
Now onward to using the attr.asdict()
function... 现在开始使用
attr.asdict()
函数...
# attr.Dict
print("asdict(mlle):", attr.asdict(mlle))
print("asdict(mlle.lle):", attr.asdict(mlle.list_of_list_of_elements)) # FAILS
print("asdict(mlle.lle[0]):", attr.asdict(mlle.list_of_list_of_elements[0]))
I am quite sure that I did something simple incorrectly as I thought I decorated ALL the nested variables with attrs
. 我很确定我做错了一些简单的事情,因为我以为我用
attrs
装饰了所有嵌套变量。
I was more perplex that the use of attr.asdict()
is not smoothly available at each dotted subvariable such that mlle
and mlle.list_of_list_of_elements[0]
works, but not the mlle.list_of_list_of_elements
in between. 我感到更加
attr.asdict()
是,在每个点mlle
变量上无法顺利使用attr.asdict()
,从而使mlle
和mlle.list_of_list_of_elements[0]
起作用,但在两者之间却没有mlle.list_of_list_of_elements
。
attr.asdict
takes an instance of an attr.s
-decorated class. attr.asdict
接受一个attr.s
装饰类的实例。 mlle
and mlle.list_of_list_of_elements[0]
are both instances of attr.s
-decorated classes. mlle
和mlle.list_of_list_of_elements[0]
都是attr.s
装饰类的实例。 mlle.list_of_list_of_elements
is not. mlle.list_of_list_of_elements
不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.