美文网首页
Python 实用语法

Python 实用语法

作者: 百里江山 | 来源:发表于2020-10-12 19:34 被阅读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")

相关文章

网友评论

      本文标题:Python 实用语法

      本文链接:https://www.haomeiwen.com/subject/zbyppktx.html