Question: Evaluate an string variable's value to a variable

Discussion in 'Python' started by Mir Nazim, Dec 21, 2008.

  1. Mir Nazim

    Mir Nazim Guest

    Just a quick question.

    For example I have

    >>> class X
    >>> ....pass


    Then I do
    >>> x = X()
    >>> x.name = 'Nazim


    Now my question is whether something like below is possible and how
    >>> y = 'name'
    >>> print x.y # How can x.y can be evaluated to x.name



    PS: In PHP this can be done by a $x->$y. I sure there is some way in
    Python also


    Thanks in advance.
     
    Mir Nazim, Dec 21, 2008
    #1
    1. Advertising

  2. Mir Nazim

    Chris Rebert Guest

    On Sat, Dec 20, 2008 at 10:49 PM, Mir Nazim <> wrote:
    > Just a quick question.
    >
    > For example I have
    >
    >>>> class X
    >>>> ....pass

    >
    > Then I do
    >>>> x = X()
    >>>> x.name = 'Nazim

    >
    > Now my question is whether something like below is possible and how
    >>>> y = 'name'
    >>>> print x.y # How can x.y can be evaluated to x.name


    print getattr(x, y) #==> Nazim

    There are also analogous setattr() and delattr() functions.

    Cheers,
    Chris

    --
    Follow the path of the Iguana...
    http://rebertia.com
     
    Chris Rebert, Dec 21, 2008
    #2
    1. Advertising

  3. Mir Nazim

    Mir Nazim Guest

    On Dec 21, 11:56 am, "Chris Rebert" <> wrote:
    > On Sat, Dec 20, 2008 at 10:49 PM, Mir Nazim <> wrote:
    > > Just a quick question.

    >
    > > For example I have

    >
    > >>>> class X
    > >>>> ....pass

    >
    > > Then I do
    > >>>> x = X()
    > >>>> x.name = 'Nazim

    >
    > > Now my question is whether something like below is possible and how
    > >>>> y = 'name'
    > >>>> print x.y   #  How can x.y can be evaluated to x.name

    >
    > print getattr(x, y) #==> Nazim
    >
    > There are also analogous setattr() and delattr() functions.
    >


    Damn Right.
    These functions simply eluded my mind for well 15 minutes

    Thanks a lot Chris.

    > Cheers,
    > Chris
    >
    > --
    > Follow the path of the Iguana...http://rebertia.com
     
    Mir Nazim, Dec 21, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. darrel
    Replies:
    8
    Views:
    441
    Michael Ramey
    Feb 11, 2004
  2. Son KwonNam
    Replies:
    4
    Views:
    7,045
    Joris Gillis
    Jan 5, 2005
  3. Ajit Goel
    Replies:
    0
    Views:
    434
    Ajit Goel
    Apr 16, 2007
  4. Ajit Goel
    Replies:
    0
    Views:
    1,215
    Ajit Goel
    Apr 16, 2007
  5. Dave B.

    Evaluate as Variable, not String?

    Dave B., Jun 14, 2004, in forum: ASP General
    Replies:
    1
    Views:
    153
    Dave B.
    Jun 14, 2004
Loading...

Share This Page