您如何以编程方式设置属性? [英] How do you programmatically set an attribute?

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

问题描述

假设我有一个python对象x和一个字符串s,如何在x上设置属性s?所以:

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'

魔术是什么?顺便说一句,此操作的目标是将对x.__getattr__()的调用缓存.

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

推荐答案

setattr(x, attr, 'magic')

有关此问题的帮助,

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

但是,您应注意(如注释中所指出),您不能对object的纯"实例执行此操作.但是很可能您有一个简单的对象子类,可以很好地工作.我强烈建议O.P.永远不要创建这样的对象实例.

However, you should note (as pointed out in a 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.

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

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