Python 实用语法

判断对象属性是否存在

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")

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。