繁体   English   中英

如何正确注释 Python 中的协作继承?

[英]How do I properly annotate cooperative inherance in Python?

假设我有这样的事情:

from typing import Mapping, Any


class Hidden:

    def __init__(self, z: float, **kwargs: Any):
        super().__init__(**kwargs)
        self.z = z


class Base:

    def __init__(self, x: int, **kwargs: Any):
        super().__init__(**kwargs)
        self.x = x


class Inherited(Base):

    def __init__(self, y: int, **kwargs: Any):
        super().__init__(**kwargs)
        self.y = y


class Final(Inherited, Hidden):
    pass

我应该如何注释它? 我尝试用TypedDict的某些用途替换Any ,但它只需要值类型。 这是我能做的最好的吗?

更新
由于Inherited需要xy来初始化,它们应该明确定义为 arguments。 kwargs 用于协作 inheritance 以允许一个 class 调用另一个的 init 而无需明确担心 arguments 的类型(此处为z:float )。 因此Any在这种情况下确实是正确的注释。

同样,为了初始化Final ,我建议使用所有必需的 arguments 定义__init__ ,即def __init__(self, x:int, y:int, z:float, **kwargs:Any)

Again here, Final can also be inherited from by other class and it doesn't care for the arguments of the derived class, but keep **kwargs:Any for cooperative inheritance compatibility

ps,很抱歉绕着同一件事转来转去。

旧答案
python 中的 kwargs 是键值对的字典,这些键值对不在该方法的明确定义的 arguments 中。 因此, **kwargs最终会收集任何foo=bar参数,其中foo不在定义的 arguments 中。
value bar几乎可以是任何东西,这就是为什么使用Any的原因,因为**表示这些值将被自然包裹在 kwargs dict 中。
不过,您可以在此处注释值bar的类型。
**kwargs:int意味着您可以传递任何未声明的键值对,只要它是一个 int。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM