Python 实用语法

2020-10-12  本文已影响0人  百里江山

判断对象属性是否存在

class my_cls:
    pass

cls = my_cls()
# 判断 cls 对象里是否存在 type 属性
if hasattr(cls, 'type'): 
    print("true")
else:
    print("false")

判断字典里是否存在某字段

data = {}
# 判断 data 字典里是否存在type字段
if 'type' in data:
    print('exist')

# 判断不存在
if 'type' not in data:
    print("not exist")

is, is not 使用

class my_cls:
    pass

c = my_cls()
if c is True:
    print("true")
elif c is not False:
    print("false")

上一篇 下一篇

猜你喜欢

热点阅读