码迷,mamicode.com
首页 > 编程语言 > 详细

【Python】字典或者对象类型中键或者属性的获取与存在性判断

时间:2018-11-04 21:20:05      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:对象类型   try   nic   pythonic   turn   obj   lse   测试   属性   

# 定义测试用对象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‘])

【Python】字典或者对象类型中键或者属性的获取与存在性判断

标签:对象类型   try   nic   pythonic   turn   obj   lse   测试   属性   

原文地址:http://blog.51cto.com/l0vesql/2312725

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!