使用isinstance 來判斷乙個物件的型別

2022-05-05 23:15:13 字數 773 閱讀 8948

#!/usr/bin/env python

# coding: utf-8

'ct_p14.py -- use isinstance() to tell the type of a value' #此處為指令碼doc文件

#print("enter something, you will see its type.") #本想用使用者輸入的方式來獲取乙個物件,可是輸入的物件進行判斷都是字串,強制轉換如果是字串又會報錯

#define the function

def displaynumtype(num):  

print(num),  

if isinstance(num, (int, long, float, str, complex)):   #使用isinstance()函式

print("is type of %s." %type(num).__name__)   #type(num).__name__ 獲取num物件的type型別

else:   

print("%s is a type unknow.")

displaynumtype(-69)

displaynumtype('55')

displaynumtype(555.7)

displaynumtype('dd')

displaynumtype('fg2369')

displaynumtype(1.6j)

displaynumtype(999999999999999999999999999999999l)

使用委託來減少if else判斷

上述 根據傳進來的語言列舉值和名字串來輸出相應語言的問候語,不過,這個方法的可擴充套件性太差了,如果以後我們需要再新增韓文版,日文版,就不得不反覆修改列舉和dowork 方法,以適應新的需求。使用委託可以解決優化此類問題。using system using system.collections.g...

使用委託來減少if else判斷

using system using system.collections.generic using system.linq using system.text namespace 13 public void sayenglish string name public enum language...

MySQL查詢資料 使用IF來判斷動態執行條件

mysql查詢資料,使用if來判斷動態執行條件格式 if expression expr true,expr false mysql的if 函式,接受三個表示式,如果第乙個表示式為true,而不是零且不為null,它將返回第二個表示式。否則,它返回第三個表示式。根據使用它的上下文,它返回數字或字串值...