- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
请注意,这类似于 How to get @property methods in asdict? .
我有一个(卡住的)嵌套数据结构,如下所示。定义了一些(纯粹)依赖于字段的属性。
import copy
import dataclasses
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class Bar:
x: int
y: int
@property
def z(self):
return self.x + self.y
@dataclass(frozen=True)
class Foo:
a: int
b: Bar
@property
def c(self):
return self.a + self.b.x - self.b.y
我可以将数据结构序列化如下:
class CustomEncoder(json.JSONEncoder):
def default(self, o):
if dataclasses and dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
return json.JSONEncoder.default(self, o)
foo = Foo(1, Bar(2,3))
print(json.dumps(foo, cls=CustomEncoder))
# Outputs {"a": 1, "b": {"x": 2, "y": 3}}
但是,我还想序列化属性(
@property
)。注意我不想使用
__post_init__
将属性转换为字段。因为我想保持数据类的卡住。
I do not want to use obj.__setattr__
to work around the frozen fields.我也不想预先计算类外属性的值并将它们作为字段传递。
class CustomEncoder2(json.JSONEncoder):
def default(self, o):
if isinstance(o, Foo):
return {
"a": o.a,
"b": o.b,
"c": o.c
}
elif isinstance(o, Bar):
return {
"x": o.x,
"y": o.y,
"z": o.z
}
return json.JSONEncoder.default(self, o)
foo = Foo(1, Bar(2,3))
print(json.dumps(foo, cls=CustomEncoder2))
# Outputs {"a": 1, "b": {"x": 2, "y": 3, "z": 5}, "c": 0} as desired
对于几级嵌套,这是可以管理的,但我希望有一个更通用的解决方案。例如,这是一个(hacky)解决方案,它对数据类库中的 _asdict_inner 实现进行猴子补丁。
def custom_asdict_inner(obj, dict_factory):
if dataclasses._is_dataclass_instance(obj):
result = []
for f in dataclasses.fields(obj):
value = custom_asdict_inner(getattr(obj, f.name), dict_factory)
result.append((f.name, value))
# Inject this one-line change
result += [(prop, custom_asdict_inner(getattr(obj, prop), dict_factory)) for prop in dir(obj) if not prop.startswith('__')]
return dict_factory(result)
elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
return type(obj)(*[custom_asdict_inner(v, dict_factory) for v in obj])
elif isinstance(obj, (list, tuple)):
return type(obj)(custom_asdict_inner(v, dict_factory) for v in obj)
elif isinstance(obj, dict):
return type(obj)((custom_asdict_inner(k, dict_factory),
custom_asdict_inner(v, dict_factory))
for k, v in obj.items())
else:
return copy.deepcopy(obj)
dataclasses._asdict_inner = custom_asdict_inner
class CustomEncoder3(json.JSONEncoder):
def default(self, o):
if dataclasses and dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
return json.JSONEncoder.default(self, o)
foo = Foo(1, Bar(2,3))
print(json.dumps(foo, cls=CustomEncoder3))
# Outputs {"a": 1, "b": {"x": 2, "y": 3, "z": 5}, "c": 0} as desired
有没有推荐的方法来实现我想要做的事情?
最佳答案
这似乎与方便的 dataclass
相矛盾特征:
Class(**asdict(obj)) == obj # only for classes w/o nested dataclass attrs
如果你没有找到任何相关的 pypi 包,你总是可以像这样添加一个 2-liner:
from dataclasses import asdict as std_asdict
def asdict(obj):
return {**std_asdict(obj),
**{a: getattr(obj, a) for a in getattr(obj, '__add_to_dict__', [])}}
然后,您可以在 dicts 中以自定义但简短的方式指定您想要的内容:
@dataclass
class A:
f: str
__add_to_dict__ = ['f2']
@property
def f2(self):
return self.f + '2'
@dataclass
class B:
f: str
print(asdict(A('f')))
print(asdict(B('f')))
:
{'f2': 'f2', 'f': 'f'}
{'f': 'f'}
关于python - 在 asdict 或序列化的数据类中包含属性的推荐方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64777931/
嗨, 我是 Spark 的新手,我正在尝试使用 ML 推荐。 我的代码 df = sqlContext.createDataFrame( [(0, 0, 4.0), (0, 1, 2.0), (1,
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
平台工程是为软件开发人员创建高效生态系统的过程,帮助他们自主执行软件开发生命周期的端到端操作。平台工程旨在减少开发人员的整体认知负荷并消除流程中的瓶颈,让开发团队的体验更佳。平台工程工具通过改善开发
最近在ubuntu系统中使用自带的firefox浏览器,发现有写问题,比如登陆后,书签,历史记录等,原本在windows下同步的数据无法同步,添加书签的功能也无法使用。 经过查询资料后得知,unb
Remax是蚂蚁开源的一个用React来开发小程序的框架,采用运行时无语法限制的方案。整体研究下来主要分为三大部分:运行时原理、模板渲染原理、编译流程;看了下现有大部分文章主要集中在Reamx的运行
实验室拟态存储的项目需要通过lvs-nat模式通过lvs服务器来区隔内外网的服务,所以安全防护的重心则落在了lvs服务器之上。笔者最终选择通过firewalld放行端口的方式来实现需求,由于fire
如今,随着我们身体各类数据的指数级增长,人们需要接受的信息量越来越大,系统必须处理的难度也是越来越高。而这些正是我们需要通过交互式图表和仪表盘,来实现数据可视化的根本原因。在大幅节省用户的时间和精力
vsftpd 是“very secure FTP daemon”的缩写,安全性是它的一个最大的特点。 vsftpd 是一个 UNIX 类操作系统上运行的服务器的名字,它可以运行在诸如 Linux、
1、实现memcpy 将src所指向的内容拷贝到dst所指向的位置,拷贝len个字节。 memcpy是内存拷贝函数 memcpy在使用的时候不用考虑类型,以字节为单位进行拷贝
现在有3台服务器 s1(主),s2(从), s3(从)需要实现文件实时同步,我们可以安装Nfs服务端和客户端来实现! 1、安装 NFS 服务器所需的软件包:
本文基于Free Code Camp基本算法脚本“查找字符串中最长的单词”。 在此算法中,我们要查看每个单词并计算每个单词中有多少个字母。然后,比较计数以确定哪个单词的字符最多,并返回最长单词的长
I/O简介 I/O是Input/output的缩写,在java中,对于数据的输入和输出以流的方式进行。java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出
目录 docker容器源码部署httpd,用存储卷部署网站 创建一个httpd镜像 部署nfs 挂载 创建容器并映射
python代码如下: import webbrowser as wbimport foliumif __name__ == '__main__': loc = [30.679943, 104.0
近日,微软在 Github 上开源了一个 Python 静态类型检查工具:pyright ,引起了社区内的多方关注。 微软在开源项目上的参与力度是越来越大了,不说收购 Github 这种大的战略野
在编写多线程代码时,经常面临线程安全退出的问题。 一般情况下,选择检查标志位的方式: 在线程的while循环中,执行完例程后,都对标志位进行检查,如果标志位指示继续执行则再次执行例程,如果标志
前言 在程序中我们经常可以看到有很多的加密算法,比如说MD5 sha1等,今天我们就来了解下这下加密算法的吧,在了解之前我们需要知道一个模块嘛就是hashlib,他就是目前Python一个提供字符
java 泛型(generics)是 jdk 5 中引入的一个新特性, 泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型。 泛型的本质是参数化类型,也就是说所操作的数据类型
在Python中,当我们有两个字典需要合并的时候,可以使用字典的 update 方法,例如: a = {'a': 1, 'b': 2} b = {'x': 3, 'y': 4}
有的时候我们在获取到目标电脑时候如果对方电脑又python 编译环境时可以利用python 反弹shell 主要用到python os库和sokect库 这里的服务端在目标机上运行
我是一名优秀的程序员,十分优秀!