温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-10-20 18:06:19 来源:网络 阅读:1032 作者:对唔住 栏目:编程语言
# 定义测试用对象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中获取参数值可以等同于从字典中获取的方式
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI