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

# 定義測試用對象A,字典B
class A(object):
    length = 10

B ={"length":10}

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

# 這種low一點
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中獲取參數值能夠等同於從字典中獲取的方式
相關文章
相關標籤/搜索