【问题标题】:How to access object attribute given string corresponding to name of that attribute如何访问与该属性名称对应的给定字符串的对象属性
【发布时间】: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


    【解决方案1】:

    有称为getattrsetattr的内置函数

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

    在这种情况下

    x = getattr(t, 'attr1')
    setattr(t, 'attr1', 21)
    

    【讨论】:

    • 还有删除属性的delattr,不过这个用的很少。
    • 和 hasattr 用于测试对象是否具有特定的属性,尽管在这种情况下使用三参数形式 getattr(object, attrname, default) 通常更好。
    • 无论如何我们可以像这样使用getattr,并说我有一个数据框df1,还有一个变量x = 'df1',即df1作为var x中的字符串。我想像这样打印 df 的形状,getattr(x, 'shape')getattr('df1', 'shape')。我知道这不能用 getattr 和任何其他方法来完成。
    • 你可以做getattr(globals()[x], 'shape')
    • @ihightower 见How to get the value of a variable given its name in a string? 简而言之,如果范围未知,则没有通用的方法。 afult 的解决方案假定它是一个全局的,尽管它可能是。
    【解决方案2】:

    如果您想将逻辑隐藏在类中,您可能更喜欢使用通用的 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可能更可取。

    【讨论】:

      【解决方案3】:

      注意:这个答案已经过时了。它适用于使用 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
      

      【讨论】:

        猜你喜欢
        • 2023-01-25
        • 2015-07-25
        • 1970-01-01
        • 2020-04-21
        相关资源
        最近更新 更多