Creating new instances of subclasses.
ptmcg at austin.rr.com
Wed Jan 7 19:00:06 CET 2009
On Jan 7, 10:38 am, "J. Cliff Dyer" <j... at unc.edu> wrote:
> I want to be able to create an object of a certain subclass, depending
> on the argument given to the class constructor.
> I have three fields, and one might need to be a StringField, one an
> IntegerField, and the last a ListField. But I'd like my class to
> delegate to the proper subclass automatically, so I can just do:
> >>> f1 = Field('abc')
> >>> f2 = Field('123')
> >>> f3 = Field('D,E,F')
O-O is not always the solution to every problem. Since inheritance is
getting in your way, try using a class-level factory method. Instead
of using the Field constructor, use a staticmethod of Field, something
and then get rid of all those __new__ methods, too.
More information about the Python-list