What is getattr() exactly and how do I use it?

前端 未结 14 1650
孤独总比滥情好
孤独总比滥情好 2020-11-22 09:04

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

14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 09:29

    getattr(object, 'x') is completely equivalent to object.x.

    There are only two cases where getattr can be useful.

    • 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.

提交回复
热议问题