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

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

笔记: 它不应该包含方法。只有田野。

有帮助吗?

解决方案

请注意,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}

更好的方法(由 罗伯特 在评论中)是内置的 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...

其他提示

代替 x.__dict__, ,实际上使用起来更Pythonic vars(x).

dir builtin 将为您提供对象的所有属性,包括特殊方法,例如 __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' }

因此可以通过定义您的方法将其扩展为仅返回数据属性而不返回方法 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

我已经解决了两个答案的组合:

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

从任意数据构建字典 目的, ,使用就足够了 __dict__.

这会丢失对象从其类继承的属性。例如,

class c(object):
    x = 3
a = c()

hasattr(a, 'x') 为 true,但 'x' 没有出现在 a.__dict__ 中

我想我需要花一些时间向您展示如何通过以下方式将对象翻译为字典 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'}"

这段代码的关键部分是 __iter__ 功能。

正如评论所解释的,我们要做的第一件事就是获取 Class 项目并阻止任何以 '__' 开头的内容。

一旦你创建了它 dict, ,那么您可以使用 update dict 函数并传入实例 __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))

迟到的答案,但为了完整性和谷歌员工的利益而提供:

def props(x):
    return dict((key, getattr(x, key)) for key in dir(x) if key not in dir(x.__class__))

这不会显示类中定义的方法,但仍会显示字段,包括分配给 lambda 的字段或以双下划线开头的字段。

我认为最简单的方法是创建一个 获取项目 类的属性。如果需要写入对象,可以创建自定义 设置属性 。这是一个例子 获取项目:

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}

字典 将对象属性生成到字典中,并且可以使用字典对象来获取您需要的项目。

如果您想列出部分属性,请覆盖 __dict__:

def __dict__(self):
    d = {
    'attr_1' : self.attr_1,
    ...
    }
    return d

# Call __dict__
d = instance.__dict__()

如果您的 instance 获取一些大块数据并且想要推送 d 像消息队列一样到Redis。

使用的缺点 __dict__ 是它浅;它不会将任何子类转换为字典。

如果您使用的是Python3.5或更高版本,您可以使用 jsons:

>>> import jsons
>>> jsons.dump(f)
{'bar': 'hello', 'baz': 'world'}

Python 3:

class DateTimeDecoder(json.JSONDecoder):

   def __init__(self, *args, **kargs):
        JSONDecoder.__init__(self, object_hook=self.dict_to_object,
                         *args, **kargs)

   def dict_to_object(self, d):
       if '__type__' not in d:
          return d

       type = d.pop('__type__')
       try:
          dateobj = datetime(**d)
          return dateobj
       except:
          d['__type__'] = type
          return d

def json_default_format(value):
    try:
        if isinstance(value, datetime):
            return {
                '__type__': 'datetime',
                'year': value.year,
                'month': value.month,
                'day': value.day,
                'hour': value.hour,
                'minute': value.minute,
                'second': value.second,
                'microsecond': value.microsecond,
            }
        if isinstance(value, decimal.Decimal):
            return float(value)
        if isinstance(value, Enum):
            return value.name
        else:
            return vars(value)
    except Exception as e:
        raise ValueError

现在您可以在自己的类中使用上面的代码:

class Foo():
  def toJSON(self):
        return json.loads(
            json.dumps(self, sort_keys=True, indent=4, separators=(',', ': '), default=json_default_format), cls=DateTimeDecoder)


Foo().toJSON() 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top