Factory pattern again

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Jul 27 06:00:24 EDT 2007


Mike Howarth a écrit :
> Hi 
> 
> I was wondering whether anyone could help me, I'm pretty new to python
> coming from a PHP background and I'm having a few products in getting my
> head round how to write the factory pattern within python.
> 
> I'm currently looking to try to return values from a db and load up the
> relevant objects, values returned are product type (I,S) and product code
> (123).
> 
> At the moment I've adapted some code I've found illustrating the factory
> method but ideally I would like to use the type to load up the relevant
> object.
> 
> Another issue I've found is that I don't seem to be able to access to the
> price attribute of each of the object. I'm sure these are very
> straightforward issues however I seem to have tied myself in knots over this
> and could do with a fresh set of 'pythonic' eyes to help me out.
> 
> registry = {}
> 
> class MetaBase(type):
>      def __init__(cls, name, bases, dict):
>          registry[name] = cls
> 
> class Product(object):
>      __metaclass__ = MetaBase
> 
> class Item(Product):
>      def __init__(self, *args, **kw): 
>          self.price = 1
>          
> class Set(Product):
>      def __init__(self, *args, **kw): 
>          self.price = 2
>          
> def factory(kind, *args, **kw):
>      return registry[kind](*args, **kw) 
>  
> 
> item = registry['Item']

This returns the Item *class*, not an instance of... So the following:

> print item.price

cannot work, since price is an instance attribute, not a class attribute.

What you want is:

item = factory('Item')
print item.price

HTH



More information about the Python-list mailing list