您好,登錄后才能下訂單哦!
# 定義測試用對象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ù)值可以等同于從字典中獲取的方式
免責(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)容。