资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

# 定义测试用对象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中获取参数值可以等同于从字典中获取的方式

当前标题:【Python】字典或者对象类型中键或者属性的获取与存在性判断
文章URL:http://cdkjz.cn/article/giedhs.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220