How to access object attribute given string corresponding to name of that attribute

后端 未结 3 1333
半阙折子戏
半阙折子戏 2020-11-21 06:37

How do you set/get the values of attributes of t given by x?

class Test:
   def __init__(self):
       self.attr1 = 1
       self.a         


        
3条回答
  •  有刺的猬
    2020-11-21 07:32

    There are built-in functions called getattr and setattr

    getattr(object, attrname)
    setattr(object, attrname, value)
    

    In this case

    x = getattr(t, 'attr1')
    setattr(t, 'attr1', 21)
    

提交回复
热议问题