在 python 类上重载 __dict__()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23252370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:35:22  来源:igfitidea点击:

Overloading __dict__() on python class

pythonclass

提问by code base 5000

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(自定义对象),并将对象作为字典取回,但这不起作用。

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

你应该超载__dict__()吗?您如何才能使用 将自定义对象转换为字典dict()

采纳答案by Martijn Pieters

__dict__is nota special method on Python objects. It is used for the attribute dictionary; dict()never uses it.

__dict__不是对Python对象的特殊方法。用于属性字典;dict()从不使用它。

Instead, you could support iteration; when dict()is passed an iterablethat produces key-value pairs, a new dictionary object with those key-value pairs is produced.

相反,您可以支持迭代;当dict()传递一个产生键值对的可迭代对象时,会产生一个带有这些键值对的新字典对象。

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

您可以通过实现一个__iter__方法来提供一个迭代器,该方法应该返回一个迭代器。将该方法实现为生成器函数就足够了:

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

Demo:

演示:

>>> 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'}

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 if you want your custom class to act like a mapping everywhere else too.

您还可以子类化dict或实现Mapping 抽象类,并且dict()可以识别其中之一并将键和值复制到新的字典对象中。这需要做更多的工作,但如果您希望自定义类也像其他任何地方的映射一样,那么这可能是值得的。

回答by letitbee

No. __dict__is a method used for introspection - it returns object attributes. What you want is a brand new method, call it as_dict, for example - that's the convention. The thing to understand here is that dictobjects don't need to be necessarily created with dictconstructor.

No.__dict__是一种用于内省的方法 - 它返回对象属性。您想要的是一种全新的方法,as_dict例如将其称为- 这是惯例。这里要理解的是,dict对象不一定需要用dict构造函数创建。