staticmethod and __call__

Luigi e Viviana Ballabio famiglia.ballabio at
Fri Dec 7 14:16:09 CET 2001


>  class ItemGenerator:
>    import random
>    rgen = random.Random()
>    items = [j for j in vars(Item).values() if isinstance(j, Item)]
>    def __call__():
>      return ItemGenerator.rgen.choice(ItemGenerator.items)
>    __call__ = staticmethod(__call__)

>  items = [ItemGenerator() for i in range(5)]

apart from the __call__-not-being-overridden issue:

since you are trying to Think in Patterns, and since what you are 
after is some kind of random Item factory, it might make more sense 
to name the above correspondingly, as in:

class Item:

class ItemFactory:
     import random
     def create():
         return ItemFactory.rgen.choice(ItemFactory.items)
     create = staticmethod(create)

items = [ItemFactory.create() for i in range(5)]

principle-of-least-surprisely yours,


More information about the Python-list mailing list