【发布时间】:2019-11-21 14:39:40
【问题描述】:
我正在使用 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')
【问题讨论】:
-
我认为 numpy 可能会做这样的事情,你可以看看它是如何工作的
-
但一般来说,像 Python 这样的语言并不是围绕声明严格类型而设计的。
-
很好的问题,但我认为这在 Python 中是不可能的,因为它是打字系统。 This somewhat related question 可能会帮助您更好地理解 Python 中的输入。
-
Python 几乎使用“鸭子类型”,这意味着在实践中,默认情况下它大多是通用的。
标签: python c++ python-3.x generics types