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

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

    If you want to keep the logic hidden inside the class, you may prefer to use a generalized getter method like so:

    class Test:
        def __init__(self):
            self.attr1 = 1
            self.attr2 = 2
    
        def get(self,varname):
            return getattr(self,varname)
    
    t = Test()
    x = "attr1"
    print ("Attribute value of {0} is {1}".format(x, t.get(x)))
    

    Outputs:

    Attribute value of attr1 is 1
    

    Another apporach that could hide it even better would be using the magic method __getattribute__, but I kept getting an endless loop which I was unable to resolve when trying to get retrieve the attribute value inside that method.

    Also note that you can alternatively use vars(). In the above example, you could exchange getattr(self,varname) by return vars(self)[varname], but getattrmight be preferable according to the answer to What is the difference between vars and setattr?.

提交回复
热议问题