问题描述
我最近了解了getattr()
函数.问题是我仍然无法理解其用法.我对getattr()
唯一了解的是getattr(li, "pop")
与调用li.pop
相同.
I've recently read about the getattr()
function. The problem is that I still can't grasp the idea of its usage. The only thing I understand about getattr()
is that getattr(li, "pop")
is the same as calling li.pop
.
当书中提到您如何使用它来获取对函数的引用时,直到运行时才知道它的名称,我不明白.总的来说,也许这是我在编程方面的菜鸟.有人可以阐明这个话题吗?我什么时候以及如何使用它?
I didn't understand when the book mentioned how you use it to get a reference to a function without knowing its name until run-time. Maybe this is me being a noob in programming, in general. Could anyone shed some light on the subject? When and how do I use this exactly?
推荐答案
getattr(object, 'x')
与object.x
完全等效.
getattr(object, 'x')
is completely equivalent to object.x
.
在只有两种情况中,getattr
可能有用.
- 您无法编写
object.x
,因为您事先不知道想要哪个属性(它来自字符串).对于元编程非常有用. - 您要提供默认值.如果没有
y
,则object.y
将引发AttributeError
.但是getattr(object, 'y', 5)
将返回5
.
- you can't write
object.x
, because you don't know in advance which attribute you want (it comes from a string). Very useful for meta-programming. - you want to provide a default value.
object.y
will raise anAttributeError
if there's noy
. Butgetattr(object, 'y', 5)
will return5
.
这篇关于确切地说,什么是getattr(),我该如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!