Python - typing 模塊 —— TypeVar 泛型


前言

typing 是在 python 3.5 才有的模塊

 

前置學習

Python 類型提示:https://www.cnblogs.com/poloyy/p/15145380.html

 

常用類型提示

https://www.cnblogs.com/poloyy/p/15150315.html

 

類型別名

https://www.cnblogs.com/poloyy/p/15153883.html 

 

NewType

https://www.cnblogs.com/poloyy/p/15153886.html

 

Callable

https://www.cnblogs.com/poloyy/p/15154008.html

 

TypeVar 泛型

源碼解析使用方式

 

任意類型

# 可以是任意類型
T = TypeVar('T')


def test(name: T) -> T:
    print(name)
    return name


test(11)
test("aa")


# 輸出結果
11
aa

 

指定類型

# 可以是 int,也可以是 str 類型
AA = TypeVar('AA', int, str)

num1: AA = 1
num2: AA = "123"
print(num1, num2)

num3: AA = []


# 輸出結果
1 123

 

自定義泛型類

暫時沒搞懂這個有什么用,先不管了

# 自定義泛型
from typing import Generic

T = TypeVar('T')


class UserInfo(Generic[T]):  # 繼承Generic[T],UserInfo[T]也就是有效類型
    def __init__(self, v: T):
        self.v = v

    def get(self):
        return self.v


l = UserInfo("小菠蘿")

print(l.get())


# 輸出結果
小菠蘿

 

Any Type

https://www.cnblogs.com/poloyy/p/15158613.html

 

Union

https://www.cnblogs.com/poloyy/p/15170066.html

 

Optional

https://www.cnblogs.com/poloyy/p/15170297.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM