你如何编程设置在Python属性? [英] How do you programmatically set an attribute in Python?

查看:150
本文介绍了你如何编程设置在Python属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Python对象 X 和一个字符串取值,我怎么设置属性取值 X ?所以:

 >>> X = SomeObject()
>>> ATTR ='myAttr
>>> #魔高一尺这​​里
>>> x.myAttr
'魔法'

有什么魔力?这样做的目的,顺便说一句,缓存调用 X .__ GETATTR __()。


解决方案

  SETATTR(X,ATTR,魔力)

有关它的帮助:

 >>>帮助(SETATTR)
帮助的模块__builtin__内置函数SETATTR:SETATTR(...)
    SETATTR(对象名称,值)    设置对象上的指定属性; SETATTR(X,'Y',v)为相当于
    ``xy格式的= V'。

编辑:但是,您应注意(在评论中指出),你不能这样对待对象的纯粹的实例。但它可能是你有对象的简单子类,它会正常工作。我强烈敦促O.P.永远不会使对象的实例这样的。

Suppose I have a python object x and a string s, how do I set the attribute s on x? So:

>>> x = SomeObject()
>>> attr = 'myAttr'
>>> # magic goes here
>>> x.myAttr
'magic'

What's the magic? The goal of this, incidentally, is to cache calls to x.__getattr__().

解决方案

setattr(x, attr, 'magic')

For help on it:

>>> help(setattr)
Help on built-in function setattr in module __builtin__:

setattr(...)
    setattr(object, name, value)

    Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    ``x.y = v''.

Edit: However, you should note (as pointed out in comment) that you can't do that to a "pure" instance of object. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.

这篇关于你如何编程设置在Python属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆