如何设置/获取t
给定的x
属性的值?
class Test:
def __init__(self):
self.attr1 = 1
self.attr2 = 2
t = Test()
x = "attr1"
最佳答案
getattr(object, attrname)
setattr(object, attrname, value)
在这种情况下
x = getattr(t, 'attr1')
setattr(t, 'attr1', 21)