Lists of attributes

Tim Peters tim at zope.com
Thu Dec 6 17:41:57 EST 2001


[Bruce Eckel]
> Sent: Thursday, December 06, 2001 2:57 PM
> If I have:
>
> class Flower:
>   def accept(self, visitor):
>     visitor.visit(self)
>   def __repr__(self):
>     return self.__class__.__name__
>
> class Gladiolus(Flower): pass
> Flower.gladiolus = Gladiolus()
>
> class Runuculus(Flower): pass
> Flower.runuculus = Runuculus()
>
> class Chrysanthemum(Flower): pass
> Flower.chrysanthemum = Chrysanthemum()
>
> Is there a clever way to get a list containing
> [Flower.gladiolus, Flower.runuculus, Flower.chrysanthemum]
>
> I've got:
> [j for i,j in Flower.__dict__.items() if Flower in
> j.__class__.__bases__]
> But I was hoping for something less awkward...

I thought your original

    [Flower.gladiolus, Flower.runuculus, Flower.chrysanthemum]

was quite elegant <wink>.

Note that new-style classes in Python 2.2 keep track of their (immediate)
subclasses, in order to speed propagating dynamic changes down the
inheritance graph (an invisible chore performed by the runtime on your
behalf).  So, in 2.2, change

    class Flower:

to

    class Flower(object):

(that makes Flower a new-style class), and later

    Flower.__subclasses__()

can be used to obtain the list [Gladiolus, Runuculus, Chrysanthemum].

mightily-impressed-by-correctly-spelled-flower-names-ly y'rs  - tim





More information about the Python-list mailing list