提问者:小点点

在python中键入类的实例[duplicate]


type[SomeType]是否有反函数,使得instance[type[SomeType]]==SomeType

给了我一个类,我想对调用它的构造函数的返回值进行注释

class FixedSizeUInt(int):
    size: int = 0
    def __new__(cls, value: int):
        cls_max: int = cls.max_value()
        if not 0 <= value <= cls_max:
            raise ValueError(f"{value} is outside range " +
                             f"[0, {cls_max}]")
        new: Callable[[cls, int], Instance[cls]] = super().__new__  ### HERE
        return new(cls, value)

    @classmethod
    def max_value(cls) -> int:
        return 2**(cls.size) - 1

编辑:这个类是抽象的,它需要被子类化才能有意义,因为0的大小只允许0作为它的值。

class NodeID(FixedSizeUInt):
    size: int = 40

class NetworkID(FixedSizeUInt):
    size: int = 64

共1个答案

匿名用户

我相信你想:

new: Callable[[Type[FixedSizeUInt], int], FixedSizeUInt] = ...

或者更动态一点:

from typing import TypeVar, Callable

T = TypeVar('T')

...

def __new__(cls: Type[T], value: int):
    ...
    new: Callable[[Type[T], int], T] = ...