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

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

    It is also clarifying from https://www.programiz.com/python-programming/methods/built-in/getattr

    class Person:
        age = 23
        name = "Adam"
    
    person = Person()
    print('The age is:', getattr(person, "age"))
    print('The age is:', person.age)
    

    The age is: 23

    The age is: 23

    class Person:
        age = 23
        name = "Adam"
    
    person = Person()
    
    # when default value is provided
    print('The sex is:', getattr(person, 'sex', 'Male'))
    
    # when no default value is provided
    print('The sex is:', getattr(person, 'sex'))
    

    The sex is: Male

    AttributeError: 'Person' object has no attribute 'sex'

提交回复
热议问题