Nul*_*oet 121 python attributes object
如何设置/获取t
给定的属性值x
.
class Test:
def __init__(self):
self.attr1 = 1
self.attr2 = 2
t = Test()
x = "attr1"
Run Code Online (Sandbox Code Playgroud)
Pra*_*are 235
getattr(object, attrname)
setattr(object, attrname, value)
Run Code Online (Sandbox Code Playgroud)
在这种情况下
x = getattr(t, 'attr1')
setattr(t, 'attr1', 21)
Run Code Online (Sandbox Code Playgroud)
如果你想将逻辑隐藏在类中,你可能更喜欢使用通用的 getter 方法,如下所示:
class Test:
def __init__(self):
self.attr1 = 1
self.attr2 = 2
def get(self,varname):
return getattr(self,varname)
t = Test()
x = "attr1"
print ("Attribute value of {0} is {1}".format(x, t.get(x)))
Run Code Online (Sandbox Code Playgroud)
输出:
Attribute value of attr1 is 1
Run Code Online (Sandbox Code Playgroud)
另一个可以更好地隐藏它的方法是使用 magic method __getattribute__
,但是当我尝试检索该方法内的属性值时,我不断陷入无限循环,无法解决该循环。
另请注意,您也可以使用vars()
. 在上面的示例中,您可以getattr(self,varname)
通过进行交换return vars(self)[varname]
,但getattr
根据和之间的区别是什么?的答案可能更可取。vars
setattr
。