相关疑难解决方法(0)

TypeVar 绑定在 TypeVar 上的解决方法?

有没有办法用 Python 的类型提示来表达这个 Scala 代码?

trait List[A] {
  def ::[B >: A](x: B): List[B]
}
Run Code Online (Sandbox Code Playgroud)

我正在努力实现这种事情

class X: pass
class Y(X): pass

ys = MyList(Y(), Y())  # inferred as MyList[Y], I know how to do this
xs = ys.extended_by(X())  # inferred as MyList[X], I don't know how to do this
Run Code Online (Sandbox Code Playgroud)

请注意,类型MyList是用初始化的,它的类型extended_by可以是任何东西。有关更多详细信息,请参阅评论。

我试过的

from __future__ import annotations
from typing import TypeVar, Generic

B = TypeVar('B')
A = TypeVar('A', bound=B)


class MyList(Generic[A]):
    def __init__(*o: A):
        ...

    def extended_by(self, …
Run Code Online (Sandbox Code Playgroud)

python types type-hinting type-bounds

13
推荐指数
1
解决办法
803
查看次数

标签 统计

python ×1

type-bounds ×1

type-hinting ×1

types ×1