相关疑难解决方法(0)

Mypy:注释函数,其中返回类型取决于参数的类型

我有一个代表标准化内存量的类。

class MemoryUnit(enum.Enum):
    """Units of memory."""

    GB = 'GB'
    TB = 'TB'
    PB = 'PB'
Run Code Online (Sandbox Code Playgroud)
class Memory(BaseModel):
    """Normalized amount of memory."""

    amount: int
    unit: MemoryUnit
Run Code Online (Sandbox Code Playgroud)

现在我想为这个班级实现基本算术。加法、减法和乘法很容易注释:

def __add__(self, other: Memory) -> Memory: ...
def __sub__(self, other: Memory) -> Memory: ...
def __mul__(self, other: int) -> Memory: ...
Run Code Online (Sandbox Code Playgroud)

不过,我对分裂有疑问。我看到除法的两个用例:

  • 除以MemoryMemory得到 a float(两个存储量之间的比率是多少)。
  • 除以Memoryint得到(如果均匀除以Memory的数量是多少)Memoryn

mypy 有没有办法用这个特定的签名来注释函数?

python type-hinting mypy python-typing

2
推荐指数
1
解决办法
1195
查看次数

标签 统计

mypy ×1

python ×1

python-typing ×1

type-hinting ×1