问题
The title basically says it all. I would like to create my own class whose instances can be used with the double asterix (**
) syntax.
I searched for this quite some time. And while I found gazillions of posts explaining how to use the ** syntax, or discussing the caveats of subclassing dict, I couldn't find a single post on how to implement this functionality in a custom class.
I also tried going through the dunder methods of a dict instance, and implemented a couple, but I didn't manage to find the correct one.
class MyClass:
def __init__(self, data: dict):
self._data = data
# now what?
a = MyClass({'foo': 1})
b = {**a}
# -> TypeError: 'MyClass' object is not a mapping
回答1:
The TypeError
told you already: it needs to be a Mapping.
You can use collections.abc
to enforce implementation of the necessary methods (namely __getitem__, __iter__, __len__
):
from collections.abc import Mapping
class Foo(Mapping):
pass
f = Foo()
# TypeError: Can't instantiate abstract class Foo with abstract methods __getitem__, __iter__, __len__
来源:https://stackoverflow.com/questions/62492107/which-dunder-methods-are-necessary-to-implement-in-a-class-to-make-it-work-with