【问题标题】:How to access (get or set) object attribute given string corresponding to name of that attribute如何访问(获取或设置)给定与该属性名称对应的字符串的对象属性
【发布时间】:2023-01-25 06:40:30
【问题描述】:

你如何设置/获取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 用于测试对象是否具有特定的 attr,尽管在这种情况下使用三个参数形式 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
      

      【讨论】:

        猜你喜欢
        • 2021-12-27
        • 2020-04-21
        相关资源
        最近更新 更多