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