How do you programmatically set an attribute?

后端 未结 4 845
北荒
北荒 2020-11-22 04:41

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

>>> x =          


        
4条回答
  •  误落风尘
    2020-11-22 05:29

    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 "", line 1, in 
    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
    

提交回复
热议问题