283

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

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

t = Test()
x = "attr1"
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Nullpoet
  • 10,949
  • 20
  • 48
  • 65

3 Answers3

491

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)
Pratik Deoghare
  • 35,497
  • 30
  • 100
  • 146
  • 23
    There is also delattr for deleting attributes, but this is rarely used. – Dave Kirby Apr 10 '10 at 07:33
  • 20
    and hasattr for testing whether or not an object has a specific attr though in that case using the three argument form getattr(object, attrname, default) is often better. – Duncan Apr 10 '10 at 11:20
  • 1
    @ihightower See [How to get the value of a variable given its name in a string?](/q/9437726/4518341) In short, there's no general way to do it if the scope is unknown. afult's solution assumes it's a global, though it probably is. – wjandrea Nov 11 '21 at 20:07
8

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?.

not2savvy
  • 2,902
  • 3
  • 22
  • 37
3

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
Community
  • 1
  • 1
aatifh
  • 2,317
  • 4
  • 27
  • 30