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

后端 未结 3 1352
半阙折子戏
半阙折子戏 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:17

    Note: This answer is very outdated. It applies to Python 2 using the new module that was deprecated in 2008.

    There is python built in functions setattr and getattr. Which can used to set and get the attribute of an class.

    A brief example:

    >>> from new import  classobj
    
    >>> obj = classobj('Test', (object,), {'attr1': int, 'attr2': int}) # Just created a class
    
    >>> setattr(obj, 'attr1', 10)
    
    >>> setattr(obj, 'attr2', 20)
    
    >>> getattr(obj, 'attr1')
    10
    
    >>> getattr(obj, 'attr2')
    20
    

提交回复
热议问题