确切地说,什么是getattr(),我该如何使用它? [英] What is getattr() exactly and how do I use it?

查看:106
本文介绍了确切地说,什么是getattr(),我该如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近了解了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 an AttributeError if there's no y. But getattr(object, 'y', 5) will return 5.

这篇关于确切地说,什么是getattr(),我该如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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