【问题标题】:How can one achieve generics in python? Something like Java or C++ offers如何在 python 中实现泛型? Java 或 C++ 之类的东西提供
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2014-03-21
    • 2016-03-30
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多