您的位置:首页 > 编程语言 > Python开发

The Python getattr Function

2016-04-11 00:00 591 查看
摘要: The Python getattr Function

Python年代getattr函数用于获取一个属性的对象,使用字符串对象,而不是一个标识符识别属性。换句话说,以下两个语句是等价的
value = obj.attribute
value = getattr(obj, "attribute")

如果属性存在,返回相应的值。如果属性不存在,你得到一个AttributeError异常。
The getattr function can be used on any object that supports dotted notation (by implementing the __getattr__ method). This includes class objects, modules, and even function objects.
getattr函数可用于任何支持点状符号的对象(通过实现__getattr__方法)。这包括类对象、模块和函数对象
path = getattr(sys, "path")
doc = getattr(len, "__doc__")

The getattr function uses the same lookup rules as ordinary attribute access, and you can use it both with ordinary attributes and methods:
getattr函数使用相同的查询规则作为普通属性访问,您可以使用它与普通的属性和方法
result = obj.method(args)

func = getattr(obj, "method")
result = func(args)

or, in one line:
result = getattr(obj, "method")(args)

Calling both getattr and the method on the same line can make it hard to handle exceptions properly. To avoid confusing AttributeError exceptions raised by getattr with similar exceptions raised inside the method, you can use the following pattern:
调用getattr和方法在同一行,那就很难正确地处理异常。为了避免混淆AttributeError异常提出getattr具有类似方法抛出的异常,您可以使用以下模式

try:
func = getattr(obj, "method") except AttributeError:
... deal with missing method ... else:
result = func(args)

The function takes an optional default value, which is used if the attribute doesn’t exist. The following example only calls the method if it exists:
函数接受一个可选的默认值,如果该属性不存在使用。下面的例子只调用该方法如果它存在

func = getattr(obj, "method", None) if func:
func(args)

Here’s a variation, which checks that the attribute is indeed a callable object before calling it.
年代的一个变种,检查属性在调用之前确实是一个可调用对象。
func = getattr(obj, "method", None) if callable(func):
func(args)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  getattr