溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

【Python】字典或者對象類型中鍵或者屬性的獲取與存在性判斷

發(fā)布時間:2020-10-20 18:06:19 來源:網(wǎng)絡(luò) 閱讀:1044 作者:對唔住 欄目:編程語言
# 定義測試用對象A,字典B
class A(object):
    length = 10

B ={"length":10}

# 判斷對象是否含有某種屬性
# 推薦這種方式,更Pythonic
try:
    x = A.lengt
except AttributeError:
    print("does not have {}".format("lengt"))

# 這種low一點(diǎn)
if "leng" in dir(A):
    print(A.length)
else:
    print("does not have {}")

# 或者這種方式
try:
    x = getattr(A,"length")
except AttributeError:
    print("does not have {}".format("lengt"))

# 判斷字典是否具有某個鍵:
try:
     x = B['ssss']
except KeyError:
   print("Not have")

# 或者
if x in x.keys():
    do something
# 或者
if  x.get('gridman'):
    do something
else 
    print("Not have")

# 獲取屬性的方式
# 對象
print(getattr(A,"length"))
print(A.length)

print(B.get("length","if not have return DefaultValue"))
print(B['length'])

# 注意
從**kwargs中獲取參數(shù)值可以等同于從字典中獲取的方式
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI