Factory pattern again

Mike Howarth hey at mikehowarth.co.uk
Fri Jul 27 08:54:00 EDT 2007


Thanks that makes absolute sense. 

I was sure it was something simple, thanks for your time.


Bruno Desthuilliers-5 wrote:
> 
> 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
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: http://www.nabble.com/Factory-pattern-again-tf4156186.html#a11828597
Sent from the Python - python-list mailing list archive at Nabble.com.




More information about the Python-list mailing list