如何在python中实现泛型?类似java或C++的东西

2024-06-30 15:07:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python处理泛型,想知道我是否能像其他语言一样用python实现泛型。语法不需要和其他语言一样,但是如果我能像


template<typename T>
class List {
public:
    T array[10];
};

int main() {
    List<int> list;
}

我尝试了下面的代码,但我不知道如何才能实现与C++或java相同的代码。比如,一旦我在初始化时定义了数据类型,就不应该允许我添加任何其他类型的对象。你知道吗


from typing import TypeVar, Generic, List

T = TypeVar('T')


class CircularQueue(Generic[T]):

    def __init__(self):
        self._front = 0
        self._rear = 0
        self._array = list()

    def mod(self, x): return (x+1) % (len(self._array)+1)

    @property
    def is_full(self):
        return self.mod(self._rear) == self.mod(self._front) + 1

    def insert(self, element: T):
        if not self.is_full:
            self._rear += 1
            self._array.append(element)


if __name__ == "__main__":
    # I want to Initialize the queue as cQueue = CircularQueue<int>()
    # Something that other compiled languauges offer
    # Is it possible to do so?
    # Or any other method so that I can restrict the type of objects.
    cQueue = CircularQueue()
    cQueue.insert(10)

    # Here I want to raise an error if I insert any other type of Object
    cQueue.insert('A')    



Tags: toself语言modifdefarraylist
1条回答
网友
1楼 · 发布于 2024-06-30 15:07:35

Python没有泛型的概念,但是可以说每个函数都是泛型的,因为参数实际上不是类型化的。这是一种duck typing方法,任何像鸭子一样走路,像鸭子一样呱呱叫的东西都被当作鸭子对待。因此,通常,“泛型”函数只会检查参数或对象是否具有所需的最小属性集,并相应地处理数据。你知道吗

相关问题 更多 >