【发布时间】:2020-09-13 03:23:47
【问题描述】:
我已经编写了以下代码。但我收到TypeError: Cannot instantiate typing.TypeVar
from typing import TypeVar, Generic, List, Tuple
T = TypeVar('T')
class MyInt:
p: int
def __init__(self, value: int):
self.p = value
class Vector(Generic[T]):
items: List[T]
def __init__(self, sz: int):
self.items = [T(0) for _ in range(sz)]
def __init__(self, l: List[T]):
self.items = l
class Matrix(Generic[T]):
items: List[Vector[T]]
def __init__(self, rw: int, cl: int):
self.items = [Vector[T](cl) for _ in range(rw)]
def __init__(self, sz: Tuple[int, int]):
rw, cl = sz
self.items = [Vector[T](cl) for _ in range(rw)]
myMatrix = Matrix[MyInt](1, 2)
当我创建Matrix[MyInt] 的实例时,我不知道如何创建MyInt 的实例。你能帮我解决这个问题吗?
【问题讨论】:
标签: python class generics generic-list