Suppose I have a python object x
and a string s
, how do I set the attribute s
on x
?所以:
>>> x = SomeObject()
>>> attr = 'myAttr'
>>> # magic goes here
>>> x.myAttr
'magic'
有什么魔力?顺便说一句,这样做的目的是缓存对 x.__getattr__()
的调用。
原文由 Nick 发布,翻译遵循 CC BY-SA 4.0 许可协议
如需帮助:
但是,您应该注意,您不能对
object
的“纯”实例执行此操作。但是很可能你有一个简单的对象子类,它可以正常工作。我会强烈敦促 OP 永远不要创建这样的对象实例。