问题:如何访问给定字符串的对象属性,该字符串对应于该属性的名称

如何设置/获取t给定的属性的值x

class Test:
   def __init__(self):
       self.attr1 = 1
       self.attr2 = 2

t = Test()
x = "attr1"

How do you set/get the values of attributes of t given by x?

class Test:
   def __init__(self):
       self.attr1 = 1
       self.attr2 = 2

t = Test()
x = "attr1"

回答 0

有称为getattr和的内置函数。setattr

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

在这种情况下

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

There are built-in functions called getattr and setattr

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

In this case

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

回答 1

注意:此答案非常过时。它适用new使用2008不推荐使用的模块的Python 2 。

有内置的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

Note: This answer is very outdated. It applies to Python 2 using the new module that was deprecated in 2008.

There is python built in functions setattr and getattr. Which can used to set and get the attribute of an class.

A brief example:

>>> 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

回答 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

可以更好地隐藏它的另一个方法是使用magic方法__getattribute__,但是我一直遇到一个无限循环,当尝试在该方法中检索属性值时,我无法解决。

另请注意,您也可以使用vars()。在上面的示例中,您可以getattr(self,varname)通过进行交换return vars(self)[varname],但getattr根据之间的区别varssetattr是最好的

If you want to keep the logic hidden inside the class, you may prefer to use a generalized getter method like so:

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)))

Outputs:

Attribute value of attr1 is 1

Another apporach that could hide it even better would be using the magic method __getattribute__, but I kept getting an endless loop which I was unable to resolve when trying to get retrieve the attribute value inside that method.

Also note that you can alternatively use vars(). In the above example, you could exchange getattr(self,varname) by return vars(self)[varname], but getattrmight be preferable according to the answer to What is the difference between vars and setattr?.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。