您知道是否有一个内置函数可以从任意对象构建字典吗?我想这样做:

>>> class Foo:
...     bar = 'hello'
...     baz = 'world'
...
>>> f = Foo()
>>> props(f)
{ 'bar' : 'hello', 'baz' : 'world' }

注意:它不应该包括方法。只有字段。


当前回答

Dataclass(来自Python 3.7)是另一个可用于将类属性转换为dict的选项。Asdict可以与数据类对象一起使用 为了转换。

例子:

@dataclass
class Point:
   x: int
   y: int

p = Point(10, 20)
asdict(p) # it returns {'x': 10, 'y': 20}

其他回答

Python 3.7+将于2023年发布

您可以将数据类装饰器添加到类中,并定义一个自定义JSON序列化器,然后是JSON。转储将工作(通过向cls提供自定义编码器)。

f=Foo()
json.dumps(f, cls=CustomJSONEncoder)

{"bar": "hello", "baz": "world", "modified": "2023-02-08T11:49:15.675837"}

可以很容易地修改定制JSON序列化器,使其与任何原生JSON不可序列化的类型兼容。

from datetime import datetime
import dataclasses
import json


@dataclasses.dataclass # <<-- add this decorator 
class Foo():
    """An example dataclass."""

    bar: str = "hello"
    baz: str = "world"
    modified: datetime = Column(DateTime(timezone=True), default=datetime.utcnow)


class CustomJSONEncoder(json.JSONEncoder): # <<-- Add this custom encoder 
    """Custom JSON encoder for the DB class."""

    def default(self, o):
        if dataclasses.is_dataclass(o): # this serializes anything dataclass can handle  
            return dataclasses.asdict(o)
        if isinstance(o, datetime): # this adds support for datetime
            return o.isoformat()
        return super().default(o)

为了进一步将其扩展到任何不可序列化的类型,在自定义编码器类中添加另一个if语句,返回可序列化的内容(例如str)。

Dataclass(来自Python 3.7)是另一个可用于将类属性转换为dict的选项。Asdict可以与数据类对象一起使用 为了转换。

例子:

@dataclass
class Point:
   x: int
   y: int

p = Point(10, 20)
asdict(p) # it returns {'x': 10, 'y': 20}

注意,Python 2.7中的最佳实践是使用新风格的类(Python 3中不需要),即。

class Foo(object):
   ...

另外,“对象”和“类”之间也有区别。要从任意对象构建字典,使用__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}

一个更好的方法(由robert在评论中建议)是内置的vars函数:

>>> vars(a)
{'c': 2, 'b': 1}

或者,根据您想做的事情,从dict继承可能会更好。那么你的类已经是一个字典,如果你愿意,你可以重写getattr和/或setattr来调用和设置字典。例如:

class Foo(dict):
    def __init__(self):
        pass
    def __getattr__(self, attr):
        return self[attr]

    # etc...

Python3.x

return dict((key, value) for key, value in f.__dict__.items() if not callable(value) and not key.startswith('__'))

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

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

def to_dict(self):
    return json.loads(json.dumps(self, default=lambda o: o.__dict__))