Python 简明教程

Python - Generics

在 Python 中,泛型是一种机制,可以用来定义可以在多种类型上操作但同时保持类型安全的功能、类或方法。通过实现泛型,可以编写可与不同数据类型一起使用的可重用代码。它确保了提升代码的灵活性并保证类型的正确性。

通常,在 Python 编程中,不需要声明变量类型。类型由分配给它的值动态确定。Python 解释器不执行类型检查,因此它可能会引发运行时异常。

Python 在 3.5 版本中引入了 type hints 来实现泛型,允许你指定变量、函数参数和返回值的预期类型。此功能有助于减少运行时错误并提高代码的可读性。

泛型通过引入类型变量来扩展类型提示的概念,类型变量表示泛型类型,当使用泛型函数或类时,它可以用特定类型替换。

Defining a Generic Function

我们来看看以下定义了一个泛型函数的示例 −

from typing import List, TypeVar, Generic
T = TypeVar('T')
def reverse(items: List[T]) -> List[T]:
   return items[::-1]

在此处,我们定义了一个称为“reverse”的泛型函数。该函数将一个列表(“List[T]”)作为参数,并返回相同类型的列表。类型变量“T”表示泛型类型,在使用该函数时,它将被替换为特定类型。

Calling the Generic Function with Different Data Types

reverse() 函数被调用,并使用了不同的数据类型 −

numbers = [1, 2, 3, 4, 5]
reversed_numbers = reverse(numbers)
print(reversed_numbers)

fruits = ['apple', 'banana', 'cherry']
reversed_fruits = reverse(fruits)
print(reversed_fruits)

它将生成以下 output

[5, 4, 3, 2, 1]
['cherry', 'banana', 'apple']

Defining a Generic Class

一个泛型类型通常通过在类名后面添加类型参数列表来声明。以下示例使用泛型类实现泛型 −

from typing import List, TypeVar, Generic
T = TypeVar('T')
class Box(Generic[T]):
   def __init__(self, item: T):
      self.item = item
   def get_item(self) -> T:
      return self.item
Let us create objects of the above generic class with int and str type
box1 = Box(42)
print(box1.get_item())

box2 = Box('Hello')
print(box2.get_item())

它将生成以下 output

42
Hello