来自对象字段的Python字典
本文翻译自:Python dictionary from an object's fields
Do you know if there is a built-in function to build a dictionary from an arbitrary object? 你知道是否有一个内置函数来从任意对象构建一个字典? I'd like to do something like this: 我想做这样的事情:
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
NOTE: It should not include methods. 注意:它不应包括方法。 Only fields. 只有字段。
#1楼
参考:https://stackoom.com/question/G0D/来自对象字段的Python字典
#2楼
Late answer but provided for completeness and the benefit of googlers: 迟到的答案,但提供了完整性和googlers的好处:
def props(x):return dict((key, getattr(x, key)) for key in dir(x) if key not in dir(x.__class__))
This will not show methods defined in the class, but it will still show fields including those assigned to lambdas or those which start with a double underscore. 这不会显示在类中定义的方法,但它仍将显示包括分配给lambdas的字段或以双下划线开头的字段。
#3楼
I think the easiest way is to create a getitem attribute for the class. 我认为最简单的方法是为类创建一个getitem属性。 If you need to write to the object, you can create a custom setattr . 如果需要写入对象,则可以创建自定义setattr 。 Here is an example for getitem : 以下是getitem的示例:
class A(object):def __init__(self):self.b = 1self.c = 2def __getitem__(self, item):return self.__dict__[item]# Usage:
a = A()
a.__getitem__('b') # Outputs 1
a.__dict__ # Outputs {'c': 2, 'b': 1}
vars(a) # Outputs {'c': 2, 'b': 1}
dict generates the objects attributes into a dictionary and the dictionary object can be used to get the item you need. dict将对象属性生成到字典中,字典对象可用于获取所需的项目。
#4楼
I thought I'd take some time to show you how you can translate an object to dict via dict(obj)
. 我想我会花一些时间向你展示你如何通过dict(obj)
将一个对象翻译成dict。
class A(object):d = '4'e = '5'f = '6'def __init__(self):self.a = '1'self.b = '2'self.c = '3'def __iter__(self):# first start by grabbing the Class itemsiters = dict((x,y) for x,y in A.__dict__.items() if x[:2] != '__')# then update the class items with the instance itemsiters.update(self.__dict__)# now 'yield' through the itemsfor x,y in iters.items():yield x,ya = A()
print(dict(a))
# prints "{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4', 'f': '6'}"
The key section of this code is the __iter__
function. 该代码的关键部分是__iter__
函数。
As the comments explain, the first thing we do is grab the Class items and prevent anything that starts with '__'. 正如评论所解释的那样,我们要做的第一件事就是抓住Class项并防止任何以'__'开头的内容。
Once you've created that dict
, then you can use the update
dict function and pass in the instance __dict__
. 一旦你创建了那个dict
,那么你可以使用update
dict函数并传入实例__dict__
。
These will give you a complete class+instance dictionary of members. 这些将为您提供完整的成员类+实例字典。 Now all that's left is to iterate over them and yield the returns. 现在剩下的就是迭代它们并产生回报。
Also, if you plan on using this a lot, you can create an @iterable
class decorator. 此外,如果您打算大量使用它,您可以创建一个@iterable
类装饰器。
def iterable(cls):def iterfn(self):iters = dict((x,y) for x,y in cls.__dict__.items() if x[:2] != '__')iters.update(self.__dict__)for x,y in iters.items():yield x,ycls.__iter__ = iterfnreturn cls@iterable
class B(object):d = 'd'e = 'e'f = 'f'def __init__(self):self.a = 'a'self.b = 'b'self.c = 'c'b = B()
print(dict(b))
#5楼
而不是x.__dict__
,使用vars(x)
实际上更加pythonic。
#6楼
If you want to list part of your attributes, override __dict__
: 如果要列出部分属性,请覆盖__dict__
:
def __dict__(self):d = {'attr_1' : self.attr_1,...}return d# Call __dict__
d = instance.__dict__()
This helps a lot if your instance
get some large block data and you want to push d
to Redis like message queue. 如果您的instance
获得一些大块数据并且您希望将d
推送到Redis(如消息队列),这会有很大帮助。
来自对象字段的Python字典相关推荐
- python字典怎么设置_在python中设置字典中的属性
在python中设置字典中的属性 是否可以在python中从字典创建一个对象,使每个键都是该对象的属性? 像这样的东西: d = { 'name': 'Oscar', 'lastName': 'Rey ...
- python以字典初始化数据_Python 简明教程 ---12,Python 字典
代码写的越急,程序跑得越慢. -- Roy Carlson 目录 Python 字典是另一种非常实用的数据结构,在Python 中用dict 表示,是英文dictionary 的缩写. >> ...
- jjson - 支持注释的 json 和 javascript 对象解析之 Python 模块
jjson - 支持注释的 json 和 javascript 对象解析模块 by Que's C++ Studio 代码请移步 github TedQue/jjson: python module ...
- Python字典使用教程:Python字典常用操作方法
1. python字典是什么? 字典是Python中比较常用的数据结构,字典中每个成员是以"键:值"对的形式存放具有映射关系的数据. 2. Python如何创建字典? 字典语法: ...
- 将嵌套的Python字典转换为对象?
我正在寻找一种优雅的方法来获取数据,该数据使用具有一些嵌套字典和列表(例如javascript样式的对象语法)的字典进行属性访问. 例如: >>> d = {'a': 1, 'b': ...
- python字典对象的方法返回字典的值列表_python对象转字典的两种实现方式示例
本文实例讲述了python对象转字典的两种实现方式.分享给大家供大家参考,具体如下: 一. 方便但不完美的__dict__ 对象转字典用到的方法为__dict__. 比如对象对象a的属性a.name= ...
- python字典和集合对象可以进行索引_Python字典和集合
1.泛映射类型 collections.abc 模块中有 Mapping 和 MutableMapping 这两个抽象类,他们的作用是为dict和其他类似的类型定义形式接口. 标准库里所有映射类型都是 ...
- python字典中的键是什么_在python字典中作为键的对象
我试图在python字典中使用一个对象作为键,但是它的行为方式让我无法完全理解. 首先,我创建一个以对象为键的字典:package_disseminators = { ContentType(&quo ...
- python对象列表转换为字典_python实现class对象转换成json/字典的方法
本文实例讲述了python实现class对象转换成json字典的方法.分享给大家供大家参考,具体如下: # -*- encoding: UTF-8 -*- class Student: name = ...
最新文章
- LinkedIn工程经理眼中的数据世界格局
- 孙正义真会玩,这个「人不是人,狗不是狗」的画面,价值上千万
- oracle vm virtualbox右ctrl切换显示模式
- 五行代码终极完美解决从IE6到Chrome所有浏览器的position:fixed;以及闪动问题
- 北大清华团队编写!200多个科学实验+视频,和爸爸一起在家做
- linux查看主机脚本,简单的bash脚本查看任意网段的在线主机
- 漫谈图神经网络 (三)
- 美术学考计算机,艺术设计专业能跨专业考计算机研究生吗?
- 厚积薄发 前端学习笔记 CSS基础篇-左侧固定,右侧自适应(或右侧固定,左侧自适应)布局方法...
- 设置广告 php,设置ecshop广告位
- 在SSRS报表中,显示图片
- charset参数 sqluldr2_利用sqluldr2导出数据和sqlldr导入数据的方法
- 最强代码审查工具报告
- Microbiome:中国科学家完成鸡肠道微生物宏基因集的构建(张和平、魏泓、秦楠点评)...
- C语言计算n阶行列式
- 新电脑如何进行磁盘分区?
- 高处的圣地 --读《消失的地平线》
- 【夜读】有些人注定不会失败
- Diskgenius分区简单教程
- 淘宝、天猫API接口
热门文章
- innodb_file_per_table 理解
- 模式识别之knn---KNN(k-nearest neighbor algorithm)--从原理到实现
- python的编码规范【摘】
- Devexpress VCL Build v2014 vol 14.2.6 发布
- 810B - 牛人是如何工作的
- 温习php一(apache和php的配置)
- 微信公众号 分享接口 签名通过 分享无效果(JSSDK自定义分享接口的策略调整)...
- 疯狂Java学习笔记(72)-----------大话程序猿面试
- MySQL主从复制原理(原理+实操)
- 使用内存硬盘(tmpfs)来加速你的网站