looping over a class attribute

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • biner

    looping over a class attribute

    Hello,
    I would like to be able to make a loop over a given class
    attributes. For example, with the following class definition :
    [color=blue][color=green][color=darkred]
    >>> class x:[/color][/color][/color]
    .... val1=1
    .... val2=2
    ....[color=blue][color=green][color=darkred]
    >>> print x.val1[/color][/color][/color]
    1[color=blue][color=green][color=darkred]
    >>> print x.val2[/color][/color][/color]
    2

    I would like to be able to make a loop like this[color=blue][color=green][color=darkred]
    >>> dir(x)[/color][/color][/color]
    ['__doc__', '__module__', 'val1', 'val2'][color=blue][color=green][color=darkred]
    >>> for i in dir(x) : print x.i[/color][/color][/color]

    and get an output like typing

    print x.__doc__
    print x__module__
    print x.var1
    print x.var2

    instead of

    Traceback (most recent call last):
    File "<stdin>", line 2, in ?
    AttributeError: class x has no attribute 'i'

    Is there a way to do this? Thanks in advance from a clueless newbie to
    the wonderful world of Python and OO programming.

    Sebastien.
    biner.sebastien @ouranos.ca
  • Aahz

    #2
    Re: looping over a class attribute

    In article <b82e5469.04031 21359.f099aa8@p osting.google.c om>,
    biner <biner.sebastie n@ouranos.ca> wrote:[color=blue]
    >
    >I would like to be able to make a loop like this[color=green][color=darkred]
    >>>> dir(x)[/color][/color]
    >['__doc__', '__module__', 'val1', 'val2'][color=green][color=darkred]
    >>>> for i in dir(x) : print x.i[/color][/color][/color]

    print getattr(x, i)
    --
    Aahz (aahz@pythoncra ft.com) <*> http://www.pythoncraft.com/

    "usenet imitates usenet" --Darkhawk

    Comment

    • Dave Benjamin

      #3
      Re: looping over a class attribute

      In article <b82e5469.04031 21359.f099aa8@p osting.google.c om>, biner wrote:[color=blue]
      > I would like to be able to make a loop like this[color=green][color=darkred]
      >>>> dir(x)[/color][/color]
      > ['__doc__', '__module__', 'val1', 'val2'][color=green][color=darkred]
      >>>> for i in dir(x) : print x.i[/color][/color][/color]

      Like Aahz said, getattr(x, i) is your ticket. However, keep in mind that the
      behavior of dir() is not guaranteed across current and future versions of
      Python. You may have better luck using x.__dict__.keys () - or in Python 2.3,
      you can get away with this:

      for i in x.__dict__: print getattr(x, i)

      Since dictionaries are their own key-iterators now.

      --
      ..:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:.
      : please talk to your son or daughter about parametric polymorphism. :

      Comment

      Working...