setattr for secondary attribute

Fredrik Lundh fredrik at pythonware.com
Mon Nov 21 02:36:43 EST 2005


Alex wrote:

> I apologize for asking  maybe a very trivial question.
> I have a new class object A with slots. One of the slots is, for
> example, object spam. Object spam, in turn, also has slots and one of
> them is attribute eggs. I need to assign a new value to eggs. In other
> words, I need to perform the following:
>
> A.spam.eggs=newValue
>
> The problem is that I have only a string s='spam.eggs' with which to
> work, so I cannot write an expression written above. I tried to use
> setattr:
>
> setattr(A, s, newValue)
>
> but this does not work. It says that object A does not have attribute
> spam.eggs

since "eggs" is an attribute of the "spam" attribute, you need to fetch
the latter first:

    setattr(getattr(A, "spam"), "eggs")

</F>






More information about the Python-list mailing list