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

前端 未结 14 1901
孤独总比滥情好
孤独总比滥情好 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:33

    Quite frequently when I am creating an XML file from data stored in a class I would frequently receive errors if the attribute didn't exist or was of type None. In this case, my issue wasn't not knowing what the attribute name was, as stated in your question, but rather was data ever stored in that attribute.

    class Pet:
        def __init__(self):
            self.hair = None
            self.color = None
    

    If I used hasattr to do this, it would return True even if the attribute value was of type None and this would cause my ElementTree set command to fail.

    hasattr(temp, 'hair')
    >>True
    

    If the attribute value was of type None, getattr would also return it which would cause my ElementTree set command to fail.

    c = getattr(temp, 'hair')
    type(c)
    >> NoneType
    

    I use the following method to take care of these cases now:

    def getRealAttr(class_obj, class_attr, default = ''):
        temp = getattr(class_obj, class_attr, default)
        if temp is None:
            temp = default
        elif type(temp) != str:
            temp = str(temp)
        return temp
    

    This is when and how I use getattr.

提交回复
热议问题