Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

dictionary - How to wrap a python dict?

I want to implement a class that will wrap -- not subclass -- the python dict object, so that when a change is detected in a backing store I can re-create the delegated dict object. I intend to check for changes in the backing store each time the dict is accessed for a read.

Supposing I was to create an object to act like this; what methods would I need to implement?


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

1 Answer

0 votes
by (71.8m points)

You can subclass the ABC (abstract base class) collections.Mapping (or collections.MutableMapping if you also want to allow code using your instances to alter the simulated/wrapped dictionary, e.g. by indexed assignment, pop, etc).

If you do so, then, as the docs I pointed to imply somewhat indirectly, the methods you need to implement are

__len__
__iter__
__getitem__

(for a Mapping) -- you should also implement

__contains__

because by delegating to the dict you're wrapping it can be done much faster than the iterating approach the ABC would have to apply otherwise.

If you need to supply a MutableMapping then you also need to implement 2 more methods:

__setitem__
__delitem__    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
...