views:

111

answers:

2
class test():
   attr1 = int
   attr2 = int

t = test()
x = "attr1"

I want to set/get value of attribute of t corresponding to x.
How do i do that ?
Thanks in advance.

+6  A: 

There is 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)
TheMachineCharmer
There is also delattr for deleting attributes, but this is rarely used.
Dave Kirby
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
A: 

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
aatifh