我怎样才能返回属性的默认值? [英] How can I return a default value for an attribute?

查看:113
本文介绍了我怎样才能返回属性的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象为MyObject ,这可能会返回。如果返回,它不会返回一个属性 ID

  A = myobject.id

所以,当myObject的是,上面一个AttributeError的结果stament:

  AttributeError异常:'NoneType'对象有没有属性'身份证'

如果为MyObject 无,那么我想 A 等于无。如何避免此异常一行语句,如:

  A =默认(myobject.id,无)


解决方案

您应该使用 GETATTR 包装,而不是直接检索 id的值

  A = GETATTR(为MyObject,ID,无)

这好像是说:我想获得的属性 ID 从对象为MyObject ,但如果有没有属性 ID 对象为MyObject ,然后返回位于代替。但它确实它可以高效地。

某些对象还支持 GETATTR 访问的格式如下:

  A = myobject.getattr('身份证',无)

按OP要求,深GETATTR'

 高清deepgetattr(OBJ,ATTR):
    递归通过一个属性链得到最终的价值。
    回报减少(GETATTR,attr.split('。'),OBJ)
#用法:
打印deepgetattr(宇宙'galaxy.solarsystem.planet.name')

简单的解释:

减少是像就地递归函数。它的作用在这种情况下使用 OBJ (宇宙)开始,然后递归得到更深层次的每个属性您尝试使用访问 GETATTR ,所以你的问题会是这样的:

A = GETATTR(GETATTR(为MyObject,ID,无),数字,无)

I have an object "myobject", which might return None. If it returns None, it won't return an attribute "id":

a = myobject.id

So when myobject is None, the stament above results in a AttributeError:

AttributeError: 'NoneType' object has no attribute 'id'

If myobject is None, then I want "a" to be equal to None. How do I avoid this exception in one line statement, such as:

a= default(myobject.id, None)

解决方案

You should use the getattr wrapper instead of directly retrieving the value of id.

a = getattr(myobject, 'id', None)

This is like saying "I would like to retrieve the attribute id from the object myobject, but if there is no attribute id inside the object myobject, then return None instead." But it does it efficiently.

Some objects also support the following form of getattr access:

a = myobject.getattr('id', None)

As per OP request, 'deep getattr':

def deepgetattr(obj, attr):
    """Recurses through an attribute chain to get the ultimate value."""
    return reduce(getattr, attr.split('.'), obj)
# usage: 
print deepgetattr(universe, 'galaxy.solarsystem.planet.name')

Simple explanation:

Reduce is like an in-place recursive function. What it does in this case is start with the obj (universe) and then recursively get deeper for each attribute you try to access using getattr, so in your question it would be like this:

a = getattr(getattr(myobject, 'id', None), 'number', None)

这篇关于我怎样才能返回属性的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆