【Python 学习笔记】optional[int]

What's optional[int] in python?

In Python, Optional[int] is a type hint that indicates a value can either be an integer (int) or None. This is useful for functions or variables where the value is not always guaranteed to be an integer and can be absent (represented by None).

The usage of Optional[int] is to provide clear and explicit type annotations in your code, making it easier to understand and maintain. Here are some common scenarios where Optional[int] might be used:

1. Function Parameters

from typing import Optional

def process_value(value: Optional[int]) -> str:
    if value is None:
        return "No value provided"
    return f"Processing value: {value}"

print(process_value(10))  # Output: Processing value: 10
print(process_value(None))  # Output: No value provided

2. Function Return Types

from typing import Optional

def find_value(data: list, key: int) -> Optional[int]:
    if key in data:
        return data[key]
    return None

result = find_value([1, 2, 3], 1)
if result is None:
    print("Key not found")
else:
    print(f"Found value: {result}")

3. Variable Annotations

from typing import Optional

value: Optional[int] = None

# Later in the code
value = 5  # Now value is an integer
value = None  # Now value is None again

4. Class Attributes

Here's a class representing a basic student record where the student's grade might not be initially assigned.

from typing import Optional

class Student:
    def __init__(self, name: str):
        self.name = name
        self.grade: Optional[int] = None  # Grade is optional and might not be set

    def assign_grade(self, grade: int) -> None:
        self.grade = grade

    def get_grade(self) -> Optional[int]:
        return self.grade

    def display_info(self) -> None:
        print(f"Student Name: {self.name}")
        if self.grade is None:
            print("Grade: Not assigned")
        else:
            print(f"Grade: {self.grade}")

# Usage
student1 = Student("John")
student1.display_info()  # Output: Student Name: John, Grade: Not assigned

student1.assign_grade(90)
student1.display_info()  # Output: Student Name: John, Grade: 90

student2 = Student("Jane")
student2.display_info()  # Output: Student Name: Jane, Grade: Not assigned

 "Answer Generated by OpenAI's ChatGPT"

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值