Creating new instances of subclasses.

Paul McGuire ptmcg at austin.rr.com
Wed Jan 7 13:00:06 EST 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
like:

@staticmethod
def make_Field(a)
    if is_list(a):
        return ListField(a)
    elif is_integer(a):
        return IntegerField(a)
    else:
        return StringField(a)

and then get rid of all those __new__ methods, too.

-- Paul



More information about the Python-list mailing list