【发布时间】:2021-12-27 18:58:58
【问题描述】:
你如何设置/获取x给定的t的属性值?
class Test:
def __init__(self):
self.attr1 = 1
self.attr2 = 2
t = Test()
x = "attr1"
【问题讨论】:
标签: python object attributes
你如何设置/获取x给定的t的属性值?
class Test:
def __init__(self):
self.attr1 = 1
self.attr2 = 2
t = Test()
x = "attr1"
【问题讨论】:
标签: python object attributes
【讨论】:
df1,还有一个变量x = 'df1',即df1作为var x中的字符串。我想像这样打印 df 的形状,getattr(x, 'shape') 或 getattr('df1', 'shape')。我知道这不能用 getattr 和任何其他方法来完成。
getattr(globals()[x], 'shape')
如果您想将逻辑隐藏在类中,您可能更喜欢使用通用的 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)))
输出:
Attribute value of attr1 is 1
另一个可以更好地隐藏它的方法是使用魔术方法__getattribute__,但我不断得到一个无限循环,在尝试检索该方法中的属性值时我无法解决。
另请注意,您也可以使用vars()。在上面的例子中,你可以用return vars(self)[varname]交换getattr(self,varname),但是根据What is the difference between vars and setattr?的答案,getattr可能更可取。
【讨论】:
new 模块的 Python 2,即 deprecated in 2008。python 内置函数 setattr 和 getattr。可以用来设置和获取类的属性。
一个简单的例子:
>>> 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
【讨论】: