如何访问(获取或设置)对象属性给定的字符串与该属性的名称相对应

发布于 2025-02-11 07:18:37 字数 520 浏览 3 评论 0原文

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

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

t = Test()
x = "attr1"

请注意,相同的技术还涵盖了从字符串中调用方法。从根本上讲,这是两个问题:访问该方法(这里只是同一问题的实例),并调用访问的内容(这很琐碎,并且工作方式与正常访问一样)。

实际上,通过使用其名称(a String)调用模块的函数也是同一问题 - 但可能并不明显地是一个模块是具有相同方式的“属性”的“对象”。

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"

Note that the same technique also covers the issue of Call method from string. Fundamentally, that is two problems: accessing the method (which is just an instance of the same problem here), and calling what was accessed (which is trivial, and works the same way as if it had been accessed normally).

In fact, Calling a function of a module by using its name (a string) is really the same problem as well - but it may not be obvious that a module is an "object" with "attributes" that work the same way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

征棹 2025-02-18 07:18:37

有bent-in功能称为 getAttr 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)
新人笑 2025-02-18 07:18:37

如果要将逻辑隐藏在班级中,则可能更喜欢使用类似的通用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

另一个可以更好地隐藏它的apporach,是使用魔术方法__ __ getAttribute __,但是当尝试检索该方法内的属性值时,我一直无法解决我无法解决的循环。

另请注意,您可以或者可以使用vars()。在上面的示例中,您可以交换getAttr(self,varname) by return vars(self)[varname],但getAttr可能是可取的根据的答案,vars 和setAttr

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

亽野灬性zι浪 2025-02-18 07:18:37

注意:这个答案已经过时了。它适用于Python 2使用new模块,该模块在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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文