Python 如何返回属性的默认值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14923465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I return a default value for an attribute?
提问by alwbtc
I have an object myobject, which might return None. If it returns None, it won't return an attribute id:
我有一个myobject可能返回的对象None。如果返回None,则不会返回属性id:
a = myobject.id
So when myobject is None, the stament above results in a AttributeError:
因此,当 myobject 是 时None,上面的语句会导致AttributeError:
AttributeError: 'NoneType' object has no attribute 'id'
If myobjectis None, then I want ato be equal to None. How do I avoid this exception in one line statement, such as:
如果myobject是 None,那么我想a等于None. 如何在一行语句中避免此异常,例如:
a = default(myobject.id, None)
采纳答案by Inbar Rose
You should use the getattrwrapper instead of directly retrieving the value of id.
您应该使用getattr包装器而不是直接检索 的值id。
a = getattr(myobject, 'id', None)
This is like saying "I would like to retrieve the attribute idfrom the object myobject, but if there is no attribute idinside the object myobject, then return Noneinstead." But it does it efficiently.
这就好比说“我想检索属性id从对象myobject,但如果没有属性id的对象中myobject,然后返回None来代替。” 但它有效地做到了。
Some objects also support the following form of getattraccess:
一些对象还支持以下getattr访问形式:
a = myobject.getattr('id', None)
As per OP request, 'deep getattr':
根据 OP 请求,'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:
简单解释:
Reduceis 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:
Reduce就像一个就地递归函数。在这种情况下,它所做的是从obj(宇宙)开始,然后递归地深入使用您尝试访问的每个属性getattr,因此在您的问题中,它会是这样的:
a = getattr(getattr(myobject, 'id', None), 'number', None)
a = getattr(getattr(myobject, 'id', None), 'number', None)
回答by Gareth Latty
The simplest way is to use the ternary operator:
最简单的方法是使用三元运算符:
a = myobject.id if myobject is not None else None
The ternary operator returns the first expression if the middle value is true, otherwise it returns the latter expression.
如果中间值为真,则三元运算符返回第一个表达式,否则返回后一个表达式。
Note that you could also do this in another way, using exceptions:
请注意,您也可以使用异常以另一种方式执行此操作:
try:
a = myobject.id
except AttributeError:
a = None
This fits the Pythonic ideal that it's easier to ask for forgiveness than permission - what is best will depend on the situation.
这符合 Pythonic 的理想,即请求宽恕比许可更容易 - 最好的方法取决于情况。
回答by hd1
try:
a = myobject.id
except AttributeError:
a = None
Will also work and is clearer, IMO
也将工作并且更清晰,IMO
回答by Anil
a=myobect.id if myobject else None
回答by shantanoo
Help on built-in function getattr in module builtins:
getattr(...) getattr(object, name[, default]) -> valueGet a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case.
关于模块 builtins 中的内置函数 getattr 的帮助:
getattr(...) getattr(object, name[, default]) -> value从对象中获取命名属性;getattr(x, 'y') 等价于 xy 给定默认参数时,当属性不存在时返回;没有它,在这种情况下会引发异常。
Following should work:
以下应该工作:
a = getattr(myobject, 'id', None)
回答by Black Diamond
in my object class you can put override
在我的对象类中,您可以放置覆盖
class Foo(object):
def __getattribute__(self, name):
if not name in self;
return None;
else:
# Default behaviour
return object.__getattribute__(self, name)
回答by matec
If you want to solve the problem in the definition of the class of myobject(like in Black Diamond's answer) you can simply define __getattr__to return None:
如果您想在类的定义中解决问题myobject(如Black Diamond 的回答),您可以简单地定义__getattr__为 return None:
class Myobject:
def __getattr__(self, name):
return None
This works because __getattr__is only called when trying to access an attribute that does not exist, whereas __getattribute__is always called first no matter the name of the attribute. (See also this SO post.)
这是有效的,因为__getattr__仅在尝试访问不存在的属性时才调用,而__getattribute__无论属性的名称如何,始终首先调用。(另请参阅此 SO 帖子。)
To try out:
尝试:
myobject = Myobject()
print myobject.id
myobject.id = 7
print myobject.id

