关于python:如何访问与该属性名称对应的给定字符串的对象属性

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

如何设置/获取x给出的t属性值?

1
2
3
4
5
6
class test():
   attr1 = int
   attr2 = int

t = test()
x ="attr1"


有称为getattrsetattr的内置函数

1
2
getattr(object, attrname)
setattr(object, attrname, value)

在这种情况下

1
2
x = getattr(t,"attr1")
setattr(t, 'attr1', 21)


有python内置函数setattr和getattr。用于设置和获取类的属性。

一个简单的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> 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