共計(jì) 423 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
type 函數(shù)用于返回一個(gè)對(duì)象的類型。
使用方法:
- 直接調(diào)用 type 函數(shù),并將需要檢查類型的對(duì)象作為參數(shù)傳入。
例如:
x = 5
print(type(x)) # 輸出:y = [1, 2, 3]
print(type(y)) # 輸出:
- 也可以在類的定義中使用 type 函數(shù),檢查一個(gè)類的類型。
例如:
class MyClass:
pass
print(type(MyClass)) # 輸出:
- 在函數(shù)中可以使用 type 函數(shù)檢查傳入?yún)?shù)的類型。
例如:
def my_function(x):
if type(x) == int:
print("參數(shù)是整數(shù)類型")
elif type(x) == str:
print("參數(shù)是字符串類型")
else:
print("參數(shù)是其他類型")
my_function(5) # 輸出:參數(shù)是整數(shù)類型
my_function("hello") # 輸出:參數(shù)是字符串類型
注意:type 函數(shù)返回的是一個(gè)類型對(duì)象,可以通過 str() 函數(shù)將其轉(zhuǎn)換為字符串形式輸出。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完