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

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

    setattr()

    We use setattr to add an attribute to our class instance. We pass the class instance, the attribute name, and the value.

    getattr()

    With getattr we retrive these values

    For example

    Employee = type("Employee", (object,), dict())
    
    employee = Employee()
    
    # Set salary to 1000
    setattr(employee,"salary", 1000 )
    
    # Get the Salary
    value = getattr(employee, "salary")
    
    print(value)
    

提交回复
热议问题