您如何以编程方式设置属性?

问题:您如何以编程方式设置属性?

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

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

魔术是什么?顺便说一下,这样做的目的是将对的调用缓存x.__getattr__()

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__().


回答 0

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。但是很可能您有一个简单的对象子类,可以很好地工作。我强烈敦促OP不要创建这样的对象实例。

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


回答 1

通常,我们为此定义类。

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

但是,您可以在一定程度上使用setattrgetattr内置函数来执行此操作。但是,它们不适用于object直接实例。

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

但是,它们确实适用于各种简单的类。

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don’t work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

回答 2

让x成为一个对象,那么你可以通过两种方式做到这一点

x.attr_name = s 
setattr(x, 'attr_name', s)

let x be an object then you can do it two ways

x.attr_name = s 
setattr(x, 'attr_name', s)