本文介绍了在python类上重载__dict __()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我想把对象作为一个字典,所以我实现这个在 __ dict __()。这是正确的吗?

I have a class where I want to get the object back as a dictionary, so I implemented this in the __dict__(). Is this correct?

我想,一旦我这样做,然后可以使用 dict

I figured once I did that, I could then use the dict (custom object), and get back the object as a dictionary, but that does not work.

如果你重载 __ dict __(),则返回对象作为字典,但不起作用。你如何使它自定义对象可以转换为字典使用 dict()

Should you overload __dict__()? How can you make it so a custom object can be converted to a dictionary using dict()?

推荐答案

__ dict __ 不是一个Python对象的特殊方法。相反,它用于属性字典。 dict()永远不会使用它。

__dict__ is not a special method on Python objects. Instead, it is used for the attribute dictionary. dict() never uses it.

dict()传递了。将该方法实现为一个生成函数就足够了:

You can provide an iterable by implementing a __iter__ method, which should return an iterator. Implementing that method as a generator function suffices:

class Foo(object):
    def __init__(self, *values):
        self.some_sequence = values

    def __iter__(self):
        for key in self.some_sequence:
            yield (key, 'Value for {}'.format(key))

演示:

>>> class Foo(object):
...     def __init__(self, *values):
...         self.some_sequence = values
...     def __iter__(self):
...         for key in self.some_sequence:
...             yield (key, 'Value for {}'.format(key))
... 
>>> f = Foo('bar', 'baz', 'eggs', 'ham')
>>> dict(f)
{'baz': 'Value for baz', 'eggs': 'Value for eggs', 'bar': 'Value for bar', 'ham': 'Value for ham'}

您还可以子类化 dict dict()可以识别,并将键和值复制到一个新的字典对象。这是一个更多的工作,但也可能值得的,如果你想让自定义类像一个映射到其他地方。

You could also subclass dict, or implement the Mapping abstract class, and dict() would recognize either and copy keys and values over to a new dictionary object. This is a little more work, but may be worth it too if you want your custom class to act like a mapping everywhere else too.

这篇关于在python类上重载__dict __()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 19:23