Jul*_*sar 309 python attributes dictionary metaprogramming object
你知道是否有一个内置函数来从任意对象构建一个字典?我想做这样的事情:
>>> class Foo:
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
Run Code Online (Sandbox Code Playgroud)
注意:它不应包括方法.只有字段.
小智 382
请注意,Python 2.7中的最佳实践是使用新式类(Python 3不需要),即
class Foo(object):
...
Run Code Online (Sandbox Code Playgroud)
此外,"对象"和"类"之间存在差异.要从任意对象构建字典,只需使用即可__dict__.通常,您将在类级别声明您的方法,在实例级别声明您的属性,所以__dict__应该没问题.例如:
>>> class A(object):
... def __init__(self):
... self.b = 1
... self.c = 2
... def do_nothing(self):
... pass
...
>>> a = A()
>>> a.__dict__
{'c': 2, 'b': 1}
Run Code Online (Sandbox Code Playgroud)
>>> vars(a)
{'c': 2, 'b': 1}
Run Code Online (Sandbox Code Playgroud)
或者,根据您想要做的事情,继承可能会很好dict.然后你的类已经是一个字典了,如果你想要你可以覆盖getattr和/或setattr调用并设置字典.例如:
class Foo(dict):
def __init__(self):
pass
def __getattr__(self, attr):
return self[attr]
# etc...
Run Code Online (Sandbox Code Playgroud)
Ber*_*pac 121
而不是x.__dict__,它实际上更加pythonic使用vars(x).
dF.*_*dF. 56
该dir内置会给你对象的所有属性,包括特殊的方法,如__str__,__dict__和一大堆其他的,你可能不希望.但你可以这样做:
>>> class Foo(object):
... bar = 'hello'
... baz = 'world'
...
>>> f = Foo()
>>> [name for name in dir(f) if not name.startswith('__')]
[ 'bar', 'baz' ]
>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__'))
{ 'bar': 'hello', 'baz': 'world' }
Run Code Online (Sandbox Code Playgroud)
所以可以通过定义你的props函数来扩展它只返回数据属性而不是方法:
import inspect
def props(obj):
pr = {}
for name in dir(obj):
value = getattr(obj, name)
if not name.startswith('__') and not inspect.ismethod(value):
pr[name] = value
return pr
Run Code Online (Sandbox Code Playgroud)
Jul*_*sar 26
我已经结合两个答案来解决:
dict((key, value) for key, value in f.__dict__.iteritems()
if not callable(value) and not key.startswith('__'))
Run Code Online (Sandbox Code Playgroud)
ind*_*ion 15
要从任意对象构建字典,只需使用即可
__dict__.
这会遗漏对象从其类继承的属性.例如,
class c(object):
x = 3
a = c()
Run Code Online (Sandbox Code Playgroud)
hasattr(a,'x')为真,但'x'不出现在.__ dict__中
Sea*_*aux 15
我想我会花一些时间向你展示你如何将一个物体翻译成dict via dict(obj).
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 items
iters = dict((x,y) for x,y in A.__dict__.items() if x[:2] != '__')
# then update the class items with the instance items
iters.update(self.__dict__)
# now 'yield' through the items
for x,y in iters.items():
yield x,y
a = A()
print(dict(a))
# prints "{'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4', 'f': '6'}"
Run Code Online (Sandbox Code Playgroud)
这段代码的关键部分是__iter__函数.
正如评论所解释的那样,我们要做的第一件事就是抓住Class项并阻止任何以'__'开头的内容.
一旦你创建了它dict,那么你可以使用updatedict函数并传入实例__dict__.
这些将为您提供完整的成员类+实例字典.现在剩下的就是迭代它们并产生回报.
此外,如果您打算大量使用它,您可以创建一个@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,y
cls.__iter__ = iterfn
return 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))
Run Code Online (Sandbox Code Playgroud)
R H*_*R H 12
使用的一个缺点__dict__是它很浅;它不会将任何子类转换为字典。
如果您使用的是 Python3.5 或更高版本,则可以使用jsons:
>>> import jsons
>>> jsons.dump(f)
{'bar': 'hello', 'baz': 'world'}
Run Code Online (Sandbox Code Playgroud)
hiz*_*l25 10
Python3.x
return dict((key, value) for key, value in f.__dict__.items() if not callable(value) and not key.startswith('__'))
Run Code Online (Sandbox Code Playgroud)
迟到的答案,但提供了完整性和googlers的好处:
def props(x):
return dict((key, getattr(x, key)) for key in dir(x) if key not in dir(x.__class__))
Run Code Online (Sandbox Code Playgroud)
这不会显示在类中定义的方法,但它仍将显示包括分配给lambdas的字段或以双下划线开头的字段.
我认为最简单的方法是为类创建一个getitem属性。如果需要写入对象,可以创建自定义setattr。这是getitem的示例:
class A(object):
def __init__(self):
self.b = 1
self.c = 2
def __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}
Run Code Online (Sandbox Code Playgroud)
dict将对象属性生成到字典中,字典对象可用于获取您需要的项目。
2021 年,对于嵌套对象/字典/json,使用 pydantic BaseModel - 将嵌套字典和嵌套 json 对象转换为 python 对象和 JSON,反之亦然:
https://pydantic-docs.helpmanual.io/usage/models/
>>> class Foo(BaseModel):
... count: int
... size: float = None
...
>>>
>>> class Bar(BaseModel):
... apple = 'x'
... banana = 'y'
...
>>>
>>> class Spam(BaseModel):
... foo: Foo
... bars: List[Bar]
...
>>>
>>> m = Spam(foo={'count': 4}, bars=[{'apple': 'x1'}, {'apple': 'x2'}])
Run Code Online (Sandbox Code Playgroud)
对象字典
>>> print(m.dict())
{'foo': {'count': 4, 'size': None}, 'bars': [{'apple': 'x1', 'banana': 'y'}, {'apple': 'x2', 'banana': 'y'}]}
Run Code Online (Sandbox Code Playgroud)
对象到 JSON
>>> print(m.json())
{"foo": {"count": 4, "size": null}, "bars": [{"apple": "x1", "banana": "y"}, {"apple": "x2", "banana": "y"}]}
Run Code Online (Sandbox Code Playgroud)
字典到对象
>>> spam = Spam.parse_obj({'foo': {'count': 4, 'size': None}, 'bars': [{'apple': 'x1', 'banana': 'y'}, {'apple': 'x2', 'banana': 'y2'}]})
>>> spam
Spam(foo=Foo(count=4, size=None), bars=[Bar(apple='x1', banana='y'), Bar(apple='x2', banana='y2')])
Run Code Online (Sandbox Code Playgroud)
JSON 到对象
>>> spam = Spam.parse_raw('{"foo": {"count": 4, "size": null}, "bars": [{"apple": "x1", "banana": "y"}, {"apple": "x2", "banana": "y"}]}')
>>> spam
Spam(foo=Foo(count=4, size=None), bars=[Bar(apple='x1', banana='y'), Bar(apple='x2', banana='y')])
Run Code Online (Sandbox Code Playgroud)
vars() 很棒,但不适用于对象的嵌套对象
将对象的嵌套对象转换为 dict:
def to_dict(self):
return json.loads(json.dumps(self, default=lambda o: o.__dict__))
Run Code Online (Sandbox Code Playgroud)
Dataclass(来自Python 3.7)是另一个选项,可用于将类属性转换为字典。asdict可以与数据类对象一起使用进行转换。
例子:
@dataclass
class Point:
x: int
y: int
p = Point(10, 20)
asdict(p) # it returns {'x': 10, 'y': 20}
Run Code Online (Sandbox Code Playgroud)