Python——Type Hinting语法

Python中的类型提示(Type Hinting)语法允许开发者在代码中指定变量、函数参数以及函数返回值的预期类型,从而提高代码的可读性和可维护性,并支持静态类型检查工具。以下是一些基本的类型提示语法示例:

  1. 变量类型提示:
age: int = 25  # 声明变量age为整数类型
name: str = "Alice"  # 声明变量name为字符串类型
is_student: bool = True  # 声明变量is_student为布尔类型
scores: List[int] = [85, 90, 95]  # 声明scores为整数列表类型,需要导入typing模块
person: dict[str, Union[str, int]] = {"name": "Bob", "age": 30}  # 声明person为字典类型,键为字符串,值为字符串或整数类型
  1. 函数参数类型提示:
from typing import List

def greet(name: str) -> str:
    return f"Hello, {name}"

def calculate_average(numbers: List[float]) -> float:
    sum_num = sum(numbers)
    return sum_num / len(numbers)

在上述例子中:

  • greet 函数期望接受一个字符串参数,并返回一个字符串。
  • calculate_average 函数期望接受一个浮点数列表,计算平均值后返回一个浮点数。
  1. 类方法和类属性类型提示:
class Person:
    def __init__(self, name: str, age: int) -> None:
        self.name: str = name
        self.age: int = age

    def introduce(self) -> str:
        return f"My name is {self.name}, and I am {self.age} years old."

在此例中,Person 类的构造函数 __init__ 需要一个字符串和一个整数作为参数,并且类的属性 nameage 分别具有类型提示为字符串和整数。introduce 方法返回一个字符串。注意类型提示也可以放在等号后面(即属性初始化处)来为类属性指定类型。

为了使用更复杂的类型,比如联合类型、可选类型、类型别名等,需要导入 typing 模块。Python 3.9及以后版本中,许多常用的类型可以直接导入,不需要再从 typing 导入。例如:

from typing import Union, Optional

def get_info(user_id: int) -> Optional[dict[str, str]]:
    # 返回用户的详细信息字典,如果没有找到则返回None
    pass

在这个例子中,get_info 函数返回一个可选的字典类型,表示可能返回一个键值对都是字符串的字典,也可能返回 None

  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
As an AI language model, I can provide information on Python 3.9 and TensorFlow 2. Here is a brief overview: Python 3.9: Python 3.9 is the latest version of the Python programming language. It was released in October 2020 and comes with several new features and improvements. Some of the notable changes include: - Improved performance: Python 3.9 comes with several performance improvements, such as faster startup times and reduced memory usage. - New syntax features: Python 3.9 introduces new syntax features such as flexible function and variable annotations, as well as improved support for dictionaries. - Improved type hinting: Type hinting has been improved in Python 3.9, making it easier to write and maintain large codebases. - Other improvements: Python 3.9 also comes with several other improvements, such as improved string methods, new modules, and better error messages. TensorFlow 2: TensorFlow is an open-source machine learning framework developed by Google. TensorFlow 2 is the latest version of the framework, released in 2019. Some of the notable changes in TensorFlow 2 include: - Eager execution: TensorFlow 2 comes with eager execution enabled by default, making it easier to debug and develop models. - Keras integration: TensorFlow 2 has tighter integration with Keras, a popular high-level neural network API. This makes it easier to build and train deep learning models. - Improved performance: TensorFlow 2 comes with several performance improvements, such as better GPU support and improved data loading. - Other improvements: TensorFlow 2 also comes with several other improvements, such as improved support for distributed training, improved support for mobile and embedded devices, and improved visualization tools. In summary, Python 3.9 and TensorFlow 2 are both powerful tools for building machine learning models. Python 3.9 provides a range of new features and improvements, while TensorFlow 2 comes with improved performance and tighter integration with Keras. Together, they provide a powerful platform for building and training machine learning models.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值