【问题标题】:Python Generic class of Matrix, I receive Cannot instantiate typing.TypeVar errorMatrix 的 Python Generic 类,我收到无法实例化打字。TypeVar 错误
【发布时间】: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


    【解决方案1】:

    您的代码有两个问题需要修复:

    首先,Python 中不能有函数重载。因此,您的多个 __init__ 声明将不起作用。作为一种解决方法,您可以定义实例化类的静态方法。我使用了fillfromList 之类的方法名称。

    为了解决与创建 TypeVar 实例相关的问题,我使用了将矩阵和向量的默认值作为参数传递的技巧。

    所以结合上述解决方案,矩阵实例化将是

    myMatrix = Matrix[MyInt].fill(1,2, MyInt(0))
    

    类实现如下所示:

    class Vector(Generic[T]):
        items: List[T]
    
        def __init__(self):
            self.items = []
    
        @staticmethod
        def fill(sz: int, default: T):
            r = Vector[T]()
            r.items = [default for _ in range(sz)]
            return r
    
        @staticmethod
        def fromList(l: List[T]):
            r = Vector[T]()
            r.items = l
            return r
    
    
    class Matrix(Generic[T]):
        items: List[Vector[T]]
    
        def __init__(self):
            self.items = []
    
        @staticmethod
        def fill(rw: int, cl:int, default:T):
            r = Matrix[T]()
            r.items = [Vector[T].fill(cl, default) for _ in range(rw)]
            return r
    
        @staticmethod
        def fill_size(sz: Tuple[int, int], default: T):
            rw, cl = sz
            return Matrix[T].fill(rw, cl, default)
    
    

    【讨论】:

      猜你喜欢
      • 2014-10-19
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 2021-01-01
      • 1970-01-01
      • 2020-07-27
      • 2014-03-16
      相关资源
      最近更新 更多