Python 简明教程

Python - Generics

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

In Python, generics is a mechanism with which you to define functions, classes, or methods that can operate on multiple types while maintaining type safety. With the implementation of Generics enable it is possible to write reusable code that can be used with different data types. It ensures promoting code flexibility and type correctness.

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

Normally, in Python programming, you don’t need to declare a variable type. The type is determined dynamically by the value assigned to it. Python’s interpreter doesn’t perform type checks and hence it may raise runtime exceptions.

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

Python introduced generics with type hints in version 3.5, allowing you to specify the expected types of variables, function arguments, and return values. This feature helps in reducing runtime errors and improving code readability.

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

Generics extend the concept of type hints by introducing type variables, which represent generic types that can be replaced with specific types when using the generic function or class.

Defining a Generic Function

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

Let us have a look at the following example that defines 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”表示泛型类型,在使用该函数时,它将被替换为特定类型。

Here, we define a generic function called 'reverse'. The function takes a list ('List[T]') as an argument and returns a list of the same type. The type variable 'T' represents the generic type, which will be replaced with a specific type when the function is used.

Calling the Generic Function with Different Data Types

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

The function reverse() function is called with different data types −

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

It will produce the following output

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

Defining a Generic Class

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

A generic type is typically declared by adding a list of type parameters after the class name. The following example uses generics with 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

It will produce the following output

42
Hello