如何set/get给定的属性的值x?
set/get
x
class Test: def __init__(self): self.attr1 = 1 self.attr2 = 2 t = Test() x = "attr1"
有称为getattr和setattr的内置函数
getattr
setattr
getattr(object, attrname) setattr(object, attrname, value)
在这种情况下
x = getattr(t, 'attr1') setattr(t, 'attr1', 21)