来自对象字段的Python字典

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函数:

>>> 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)

  • 对不起,我来这么晚了,但不应该`vars(a)`做到这一点?对我来说,最好直接调用`__dict__`. (46认同)
  • 如果对象使用插槽(或在C模块中定义),则`__dict__`将不起作用. (11认同)
  • 如果A的一个属性具有自定义吸气剂会发生什么?(带有@property装饰器的函数)?它仍然显示在____dict____吗?它的价值是什么? (2认同)
  • 对于第二个示例,最好执行__getattr__ = dict .__ getitem__`来精确复制行为,然后您还希望`__setattr__ = dict .__ setitem__`和`__delattr__ = dict .__ delitem__`以获得完整性。 (2认同)

Ber*_*pac 121

而不是x.__dict__,它实际上更加pythonic使用vars(x).

  • 首先,Python 通常避免直接调用 dunder 项,并且几乎总是有一个方法或函数(或运算符)来间接访问它。一般来说,dunder 属性和方法是一个实现细节,使用“wrapper”函数可以让您将两者分开。其次,通过这种方式,您可以覆盖“vars”函数并引入附加功能,而无需更改对象本身。 (4认同)
  • 如果你的类使用 __slots__ ,它仍然会失败。 (4认同)
  • 同意.请注意,您还可以通过键入`MyClass(**my_dict)`来转换另一种方式(dict-> class),假设您已经定义了一个带有镜像类属性的参数的构造函数.无需访问私有属性或覆盖dict. (2认同)
  • 你能解释一下为什么它更像 Pythonic 吗? (2认同)

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)


Sco*_*der 7

迟到的答案,但提供了完整性和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的字段或以双下划线开头的字段.


rad*_*tek 6

我认为最简单的方法是为类创建一个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将对象属性生成到字典中,字典对象可用于获取您需要的项目。


Ree*_*erg 6

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)


Ric*_*evi 5

vars() 很棒,但不适用于对象的嵌套对象

将对象的嵌套对象转换为 dict:

def to_dict(self):
    return json.loads(json.dumps(self, default=lambda o: o.__dict__))
Run Code Online (Sandbox Code Playgroud)


Sur*_*eja 5

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)