Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

Overloading __dict__() on python class

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?

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.

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

question from:https://stackoverflow.com/questions/23252370/overloading-dict-on-python-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...