super().__init__(…) in mixins fails with `Too many arguments for “__init__” of “object” `

回眸只為那壹抹淺笑 提交于 2020-01-02 19:28:09

问题


When I create a mixin class that extends the logic of __init__, the regular thing to do is:

class ExtraValuemixin:

    def __init__(self, *args, **kwargs)  -> None:
        super().__init__(*args, **kwargs)
        # some extra initialization
        self._extra_value = 1

    def retrieve_extra_value(self):
        return self._extra_value

However this looks wrong to mypy, as it says:

Too many arguments for "__init__" of "object"

I get it, there's no *args or **kwargs in the object's constructor signature; but this is a mixin, and it relies on its childen's constructors. Ho do I make mypy understand this?

Full example:

class ExtraValuemixin:

    def __init__(self, *args, **kwargs)  -> None:
        super().__init__(*args, **kwargs)
        # some extra initialization
        self._extra_value = 1

    def retrieve_extra_value(self):
        return self._extra_value


class ParentObj:

    def __init__(self, value):
        self.value = value


class ChildObj(ExtraValuemixin, ParentObj):
    pass


obj = ChildObj(value=5)

print(obj.retrieve_extra_value())

来源:https://stackoverflow.com/questions/53264151/super-init-in-mixins-fails-with-too-many-arguments-for-init-o

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