Which dunder methods are necessary to implement in a class to make it work with the double asterix syntax? [duplicate]

五迷三道 提交于 2020-08-07 07:44:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!